1use std::fmt::Write as _;
22use std::iter::once;
23
24use crate::util::hash::*;
25use crate::util::intcode::*;
26use crate::util::parse::*;
27use crate::util::point::*;
28
29type Input = (FastSet<Point>, i64);
30
31struct Movement<'a> {
32 routine: String,
33 functions: [Option<&'a str>; 3],
34}
35
36pub fn parse(input: &str) -> Input {
38 let code: Vec<_> = once(2).chain(input.iter_signed().skip(1)).collect();
41 let mut computer = Computer::new(&code);
42
43 let mut x = 0;
44 let mut y = 0;
45 let mut scaffold = FastSet::new();
46 let mut position = ORIGIN;
47 let mut direction = ORIGIN;
48
49 while let State::Output(next) = computer.run() {
50 let next = next as u8;
51 let point = Point::new(x, y);
52
53 match next {
54 b'\n' => {
55 y += 1;
56 x = 0;
57 continue;
58 }
59 b'#' => {
60 scaffold.insert(point);
61 }
62 b'<' | b'>' | b'^' | b'v' => {
63 scaffold.insert(point);
64 position = point;
65 direction = Point::from(next);
66 }
67 _ => (),
68 }
69
70 x += 1;
71 }
72
73 let path = build_path(&scaffold, position, direction);
75 let mut movement = Movement { routine: String::new(), functions: [None; 3] };
76
77 compress(&path, &mut movement);
78
79 let rules: String = once(movement.routine.as_str())
81 .chain(movement.functions.into_iter().flatten())
82 .flat_map(|s| [s.trim_end_matches(','), "\n"])
83 .collect();
84
85 computer.input_ascii(&rules);
86 let score = visit(computer);
87
88 (scaffold, score)
89}
90
91pub fn part1(input: &Input) -> i32 {
92 let (scaffold, _) = input;
93 scaffold
94 .iter()
95 .filter(|&point| ORTHOGONAL.iter().all(|&delta| scaffold.contains(&(*point + delta))))
96 .map(|point| point.x * point.y)
97 .sum()
98}
99
100pub fn part2(input: &Input) -> i64 {
101 input.1
102}
103
104fn build_path(scaffold: &FastSet<Point>, mut position: Point, mut direction: Point) -> String {
108 let mut path = String::new();
109
110 loop {
111 let left = direction.counter_clockwise();
112 let right = direction.clockwise();
113
114 if scaffold.contains(&(position + left)) {
115 direction = left;
116 } else if scaffold.contains(&(position + right)) {
117 direction = right;
118 } else {
119 break path;
120 }
121
122 let mut next = position + direction;
123 let mut magnitude = 0;
124
125 while scaffold.contains(&next) {
126 position = next;
127 next += direction;
128 magnitude += 1;
129 }
130
131 let direction = if direction == left { 'L' } else { 'R' };
132 let _ = write!(path, "{direction},{magnitude},");
133 }
134}
135
136fn compress<'a>(path: &'a str, movement: &mut Movement<'a>) -> bool {
142 if path.is_empty() {
144 return true;
145 }
146 if movement.routine.len() > 21 {
148 return false;
149 }
150
151 for (i, &name) in ['A', 'B', 'C'].iter().enumerate() {
152 movement.routine.push(name);
153 movement.routine.push(',');
154
155 if let Some(needle) = movement.functions[i] {
156 if let Some(remaining) = path.strip_prefix(needle)
158 && compress(remaining, movement)
159 {
160 return true;
161 }
162 } else {
163 for (needle, remaining) in segments(path) {
165 movement.functions[i] = Some(needle);
166 if compress(remaining, movement) {
167 return true;
168 }
169 movement.functions[i] = None;
170 }
171 }
172
173 movement.routine.pop();
174 movement.routine.pop();
175 }
176
177 false
178}
179
180fn segments(path: &str) -> impl Iterator<Item = (&str, &str)> {
182 path.bytes()
183 .enumerate()
184 .filter_map(|(i, b)| (b == b',').then_some(i))
186 .take_while(|&i| i < 21)
188 .map(|i| path.split_at(i + 1))
190 .skip(1)
192 .step_by(2)
193}
194
195#[cfg(not(feature = "frivolity"))]
196fn visit(mut computer: Computer) -> i64 {
197 computer.input_ascii("n\n");
199
200 let mut result = 0;
201 while let State::Output(next) = computer.run() {
202 result = next;
203 }
204 result
205}
206
207#[cfg(feature = "frivolity")]
209fn visit(mut computer: Computer) -> i64 {
210 use std::thread::sleep;
211 use std::time::Duration;
212
213 use crate::util::ansi::*;
214
215 let mut result = 0;
216 let mut previous = ' ';
217 let mut buffer = String::new();
218
219 computer.input_ascii("y\n");
221
222 while let State::Output(next) = computer.run() {
223 result = next;
224 let ascii = char::from(next as u8);
225
226 match ascii {
228 '^' | 'v' | '<' | '>' => {
229 let _ = write!(&mut buffer, "{BOLD}{YELLOW}{ascii}{RESET}");
230 }
231 _ => buffer.push(ascii),
232 }
233
234 if ascii == '\n' && previous == '\n' {
236 print!("{HOME}{CLEAR}{buffer}");
237 sleep(Duration::from_millis(25));
238 buffer.clear();
239 }
240
241 previous = ascii;
242 }
243
244 result
245}