1use crate::util::intcode::*;
7use crate::util::parse::*;
8
9type Input = (i64, i64);
10
11pub fn parse(input: &str) -> Input {
12 let code: Vec<_> = input.iter_signed().collect();
13 let mut network = Vec::from_fn(50, |address| {
14 let mut computer = Computer::new(&code);
15 computer.input(address as i64);
16 computer
17 });
18
19 let mut nat_x = 0;
20 let mut nat_y = 0;
21 let mut first_y = None;
22 let mut idle_y = None;
23
24 loop {
25 let mut empty = 0;
26
27 for index in 0..50 {
28 let computer = &mut network[index];
29
30 match computer.run() {
31 State::Output(address) => {
32 let State::Output(x) = computer.run() else { unreachable!() };
34 let State::Output(y) = computer.run() else { unreachable!() };
35
36 if address == 255 {
37 first_y.get_or_insert(y);
39 nat_x = x;
40 nat_y = y;
41 } else {
42 let destination = &mut network[address as usize];
43 destination.input(x);
44 destination.input(y);
45 }
46 }
47 State::Input => {
49 empty += 1;
50 computer.input(-1);
51 }
52 State::Halted => unreachable!(),
53 }
54 }
55
56 if empty == 50 {
57 if idle_y == Some(nat_y) {
58 break (first_y.unwrap(), nat_y);
59 }
60 idle_y = Some(nat_y);
61
62 let destination = &mut network[0];
63 destination.input(nat_x);
64 destination.input(nat_y);
65 }
66 }
67}
68
69pub fn part1(input: &Input) -> i64 {
70 input.0
71}
72
73pub fn part2(input: &Input) -> i64 {
74 input.1
75}