Implement day 23

This commit is contained in:
2021-07-03 17:57:40 +02:00
parent 3f8c9505c3
commit ca43475a44
2 changed files with 81 additions and 0 deletions

78
2019/aoc2019/day23.py Normal file
View File

@@ -0,0 +1,78 @@
from typing import TextIO
from aoc2019.intcode import read_program, Computer
def part1(data: TextIO) -> int:
program = read_program(data)
computers = [Computer(program.copy()) for _ in range(50)]
for i, computer in enumerate(computers):
computer.send_input(i)
while True:
for computer in computers:
try:
computer.run()
except IndexError:
computer.send_input(-1)
while len(computer.output) >= 3:
dest = computer.get_output()
x = computer.get_output()
y = computer.get_output()
if dest == 255:
return y
computers[dest].send_input(x)
computers[dest].send_input(y)
def part2(data: TextIO) -> int:
program = read_program(data)
computers = [Computer(program.copy()) for _ in range(50)]
for i, computer in enumerate(computers):
computer.send_input(i)
nat_value = None
last_sent = None
while True:
is_idle = True
for computer in computers:
try:
computer._execute_current()
is_idle = False
except IndexError:
computer.send_input(-1)
try:
computer.run()
except IndexError:
pass
while len(computer.output) >= 3:
dest = computer.get_output()
x = computer.get_output()
y = computer.get_output()
if dest == 255:
nat_value = (x, y)
else:
computers[dest].send_input(x)
computers[dest].send_input(y)
if is_idle:
x, y = nat_value
if last_sent == nat_value:
return y
else:
computers[0].send_input(x)
computers[0].send_input(y)
last_sent = nat_value

View File

@@ -76,6 +76,9 @@ class Computer:
def get_output(self) -> int:
return self.output.popleft()
def send_input(self, data: int):
self.input.append(data)
def _execute_current(self) -> bool:
"""
Execute a single instruction