Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from itertools import permutations
- def getval(param, mem, index, jump):
- return mem[mem[index+jump]] if not param else mem[index+jump]
- def computer(memory, inputs):
- mem = memory[0]
- ind = memory[1]
- 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[mem[ind+3]] = getval(param1, mem, ind, 1) + getval(param2, mem, ind, 2)
- ind += 4
- elif opcode == 2:
- mem[mem[ind+3]] = getval(param1, mem, ind, 1) * getval(param2, mem, ind, 2)
- ind += 4
- elif opcode == 3:
- if len(inputs):
- mem[mem[ind + 1]] = inputs.pop(0)
- ind += 2
- else:
- memory[1] = ind
- return outputs
- elif opcode == 4:
- outputs.append(getval(param1, mem, ind, 1))
- ind += 2
- elif opcode == 5:
- ind = getval(param2, mem, ind, 2) if getval(param1, mem, ind, 1) else (ind + 3)
- elif opcode == 6:
- ind = getval(param2, mem, ind, 2) if not getval(param1, mem, ind, 1) else (ind + 3)
- elif opcode == 7:
- mem[mem[ind + 3]] = 1 if getval(param1, mem, ind, 1) < getval(param2, mem, ind, 2) else 0
- ind += 4
- elif opcode == 8:
- mem[mem[ind + 3]] = 1 if getval(param1, mem, ind, 1) == getval(param2, mem, ind, 2) else 0
- ind += 4
- elif opcode == 99:
- outputs.append('halt')
- return outputs
- with open('inputs.txt') as f:
- memory = list(map(int, f.readline().split(',')))
- signal = 0
- for phases in list(permutations ([i for i in range(5,10)])):
- mems = list()
- for _ in range(5):
- mems.append([memory[:],0])
- outputs = None
- i = 0
- for phase in phases:
- if not outputs :
- inputs = [phase,0]
- else:
- inputs = [phase] + outputs
- outputs = computer(mems[i], inputs)
- i = (i+1) % 5
- while 'halt' not in outputs:
- inputs = outputs
- outputs = computer(mems[i], inputs)
- i = (i+1) % 5
- outputs.pop(outputs.index('halt'))
- for i in range(1,5):
- inputs = outputs
- outputs = computer(mems[i], inputs)
- if 'halt' in outputs:
- outputs.pop(outputs.index('halt'))
- if 'halt' in outputs:
- outputs.pop(outputs.index('halt'))
- signal = max(signal, max(outputs))
- print(signal)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement