Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def getval(param, mem, index, jump, base):
- if param == 0:
- return mem[mem[index+jump]]
- elif param == 1:
- return mem[index+jump]
- elif param == 2:
- return mem[mem[index+jump]+base]
- def getdest(param, mem, index, jump, base):
- if param == 0:
- dest = mem[index+jump]
- elif param == 1:
- dest = index + jump
- elif param == 2:
- dest = mem[index+jump] + base
- return dest
- def computer(memory, inputs):
- mem = memory[0]
- mem += [0]*max(mem)
- ind = memory[1]
- base = memory[2]
- outputs = list()
- while True:
- instruction = (str(mem[ind])).zfill(5)
- param3 = int(instruction[0])
- param2 = int(instruction[1])
- param1 = int(instruction[2])
- opcode = int(instruction[3:])
- if opcode == 1:
- mem[getdest(param3, mem, ind, 3, base)] = getval(param1, mem, ind, 1, base) + getval(param2, mem, ind, 2, base)
- ind += 4
- elif opcode == 2:
- mem[getdest(param3, mem, ind, 3, base)] = getval(param1, mem, ind, 1, base) * getval(param2, mem, ind, 2, base)
- ind += 4
- elif opcode == 3:
- if len(inputs):
- mem[getdest(param1, mem, ind, 1, base)] = inputs.pop(0)
- ind += 2
- else:
- memory[1] = ind
- return outputs
- elif opcode == 4:
- outputs.append(getval(param1, mem, ind, 1, base))
- ind += 2
- elif opcode == 5:
- ind = getval(param2, mem, ind, 2, base) if getval(param1, mem, ind, 1, base) else (ind + 3)
- elif opcode == 6:
- ind = getval(param2, mem, ind, 2, base) if not getval(param1, mem, ind, 1, base) else (ind + 3)
- elif opcode == 7:
- mem[getdest(param3, mem, ind, 3, base)] = 1 if getval(param1, mem, ind, 1, base) < getval(param2, mem, ind, 2, base) else 0
- ind += 4
- elif opcode == 8:
- mem[getdest(param3, mem, ind, 3, base)] = 1 if getval(param1, mem, ind, 1, base) == getval(param2, mem, ind, 2, base) else 0
- ind += 4
- elif opcode == 9:
- base += getval(param1, mem, ind, 1, base)
- ind += 2
- elif opcode == 99:
- outputs.append('halt')
- return outputs
- else:
- print("invalid opcode: {0}".format(opcode))
- break
- with open('inputs.txt') as f:
- memory = list(map(int, f.readline().split(',')))
- print(computer([memory, 0, 0], [2]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement