Advertisement
jangxx

Untitled

Dec 23rd, 2019
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. from util import intcode
  2.  
  3. class Computer:
  4.     def __init__(self, memory, address):
  5.         self.cpu = intcode.runIntcodeGen(memory, input_fn=self.getInput, always_yield=False)
  6.         self.outPackets = []
  7.         self._addr = address
  8.         self._curPkt = []
  9.         self.running = True
  10.         self.inQueue = [ address ]
  11.  
  12.     def getInput(self):
  13.         print("Input {} requested".format(self._addr))
  14.  
  15.         if len(self.inQueue) > 0:
  16.             print("Input {}: {}".format(self._addr, self.inQueue[0]))
  17.             return self.inQueue.pop(0)
  18.         else:
  19.             print("Input {}: {}".format(self._addr, -1))
  20.             self.running = False
  21.             return -1
  22.  
  23.     # def step(self):
  24.     #     for outVal in self.cpu:
  25.     #         print("Output {}: {}".format(self._addr, outVal))
  26.  
  27.     def step(self):
  28.         outVal = next(self.cpu, None)
  29.  
  30.         if outVal != None:
  31.             print("Output {}: {}".format(self._addr, outVal))
  32.             self._curPkt.append(outVal)
  33.             if len(self._curPkt) == 3:
  34.                 self.outPackets.append(tuple(self._curPkt))
  35.                 self._curPkt = []
  36.  
  37. with open("inputs/input09.txt") as file:
  38.     tape = list(map(lambda x: int(x), file.read().split(",")))
  39.  
  40.     computers = []
  41.  
  42.     for i in range(50):
  43.         computers.append(Computer(tape, i))
  44.  
  45.     ether = []
  46.     i = 0
  47.     stillRunning = True
  48.  
  49.     while stillRunning:
  50.         stillRunning = False
  51.  
  52.         for c in computers:
  53.             if c.running:
  54.                 stillRunning = True
  55.                 c.step()
  56.  
  57.         # gather all sent packets
  58.         for c in computers:
  59.             if len(c.outPackets) > 0:
  60.                 ether += c.outPackets
  61.                 c.outPackets = []
  62.  
  63.         # distribute packets to their respective receivers
  64.         for pkt in ether:
  65.             addr, x, y = pkt
  66.  
  67.             if addr == 255:
  68.                 print(y)
  69.                 exit()
  70.  
  71.             computers[addr].running = True
  72.             computers[addr].inQueue += [ x, y ]
  73.  
  74.         print(i, ether)
  75.  
  76.         ether = []
  77.         i += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement