Day 23 part 2

This commit is contained in:
Dece 2019-12-23 13:07:43 +01:00
parent 4c77d7b901
commit ac21d58606

View file

@ -1,5 +1,6 @@
from queue import Empty, SimpleQueue from queue import Empty, SimpleQueue
from threading import Thread from threading import Thread
import time
from intcode import Intcode from intcode import Intcode
@ -7,19 +8,41 @@ from intcode import Intcode
def main(): def main():
codes = Intcode.parse_file("day23.txt") codes = Intcode.parse_file("day23.txt")
network = Network(50, codes) network = Network(50, codes)
# Part 1
for nic in network.nics: for nic in network.nics:
thread = Thread(target=lambda: nic.run(), name=f"NIC {nic.address}") thread = Thread(target=lambda: nic.run(), name=f"NIC {nic.address}")
thread.start() thread.start()
# Part 2
last_nat_y = None
while True:
time.sleep(0.1)
for nic in network.nics:
if not nic.inq.empty:
break
else:
if not network.last_nat_packet:
continue
x, y = network.last_nat_packet
if y == last_nat_y:
exit(f"Sending another {y} from NAT.")
last_nat_y = y
print(f"Network is idle, sending NAT packet to 0.")
network.nics[0].inq.put(x)
network.nics[0].inq.put(y)
class Network: class Network:
def __init__(self, size, codes): def __init__(self, size, codes):
self.nics = [NIC(address, self, codes) for address in range(size)] self.nics = [NIC(address, self, codes) for address in range(size)]
self.last_nat_packet = None
def route(self, sender, dest, x, y): def route(self, sender, dest, x, y):
if dest == 255: if dest == 255:
print(f"Packet to 255: {x, y}.") print(f"NAT: {x, y}.")
self.last_nat_packet = (x, y)
return return
print(f"Send {x, y} from {sender} to {dest}") print(f"Send {x, y} from {sender} to {dest}")
self.nics[dest].inq.put(x) self.nics[dest].inq.put(x)