Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from util import intcode
- class Computer:
- def __init__(self, memory, address):
- self.cpu = intcode.runIntcodeGen(memory, input_fn=self.getInput, always_yield=False)
- self.outPackets = []
- self._addr = address
- self._curPkt = []
- self.running = True
- self.inQueue = [ address ]
- def getInput(self):
- print("Input {} requested".format(self._addr))
- if len(self.inQueue) > 0:
- print("Input {}: {}".format(self._addr, self.inQueue[0]))
- return self.inQueue.pop(0)
- else:
- print("Input {}: {}".format(self._addr, -1))
- self.running = False
- return -1
- # def step(self):
- # for outVal in self.cpu:
- # print("Output {}: {}".format(self._addr, outVal))
- def step(self):
- outVal = next(self.cpu, None)
- if outVal != None:
- print("Output {}: {}".format(self._addr, outVal))
- self._curPkt.append(outVal)
- if len(self._curPkt) == 3:
- self.outPackets.append(tuple(self._curPkt))
- self._curPkt = []
- with open("inputs/input09.txt") as file:
- tape = list(map(lambda x: int(x), file.read().split(",")))
- computers = []
- for i in range(50):
- computers.append(Computer(tape, i))
- ether = []
- i = 0
- stillRunning = True
- while stillRunning:
- stillRunning = False
- for c in computers:
- if c.running:
- stillRunning = True
- c.step()
- # gather all sent packets
- for c in computers:
- if len(c.outPackets) > 0:
- ether += c.outPackets
- c.outPackets = []
- # distribute packets to their respective receivers
- for pkt in ether:
- addr, x, y = pkt
- if addr == 255:
- print(y)
- exit()
- computers[addr].running = True
- computers[addr].inQueue += [ x, y ]
- print(i, ether)
- ether = []
- i += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement