diff --git a/2019/aoc2019/day23.py b/2019/aoc2019/day23.py new file mode 100644 index 0000000..989a165 --- /dev/null +++ b/2019/aoc2019/day23.py @@ -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 diff --git a/2019/aoc2019/intcode.py b/2019/aoc2019/intcode.py index d90fac9..6b060a1 100644 --- a/2019/aoc2019/intcode.py +++ b/2019/aoc2019/intcode.py @@ -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