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_suffix(','), "\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 magnitude = 0;
123
124 while scaffold.contains(&(position + direction)) {
125 position += direction;
126 magnitude += 1;
127 }
128
129 let direction = if direction == left { 'L' } else { 'R' };
130 write!(path, "{direction},{magnitude},").unwrap();
131 }
132}
133
134fn compress<'a>(path: &'a str, movement: &mut Movement<'a>) -> bool {
140 if path.is_empty() {
142 return true;
143 }
144 if movement.routine.len() > 21 {
146 return false;
147 }
148
149 for (i, &name) in ['A', 'B', 'C'].iter().enumerate() {
150 movement.routine.push(name);
151 movement.routine.push(',');
152
153 if let Some(needle) = movement.functions[i] {
154 if let Some(remaining) = path.strip_prefix(needle)
156 && compress(remaining, movement)
157 {
158 return true;
159 }
160 } else {
161 for (needle, remaining) in segments(path) {
163 movement.functions[i] = Some(needle);
164 if compress(remaining, movement) {
165 return true;
166 }
167 movement.functions[i] = None;
168 }
169 }
170
171 movement.routine.pop();
172 movement.routine.pop();
173 }
174
175 false
176}
177
178fn segments(path: &str) -> impl Iterator<Item = (&str, &str)> {
180 path.bytes()
181 .enumerate()
182 .filter_map(|(i, b)| (b == b',').then_some(i))
184 .take_while(|&i| i < 21)
186 .map(|i| path.split_at(i + 1))
188 .skip(1)
190 .step_by(2)
191}
192
193#[cfg(not(feature = "frivolity"))]
194fn visit(mut computer: Computer) -> i64 {
195 computer.input_ascii("n\n");
197
198 let mut result = 0;
199 while let State::Output(next) = computer.run() {
200 result = next;
201 }
202 result
203}
204
205#[cfg(feature = "frivolity")]
207fn visit(mut computer: Computer) -> i64 {
208 use std::thread::sleep;
209 use std::time::Duration;
210
211 use crate::util::ansi::*;
212
213 let mut result = 0;
214 let mut previous = ' ';
215 let mut buffer = String::new();
216
217 computer.input_ascii("y\n");
219
220 while let State::Output(next) = computer.run() {
221 result = next;
222 let ascii = char::from(next as u8);
223
224 match ascii {
226 '^' | 'v' | '<' | '>' => write!(buffer, "{BOLD}{YELLOW}{ascii}{RESET}").unwrap(),
227 _ => buffer.push(ascii),
228 }
229
230 if ascii == '\n' && previous == '\n' {
232 print!("{HOME}{CLEAR}{buffer}");
233 sleep(Duration::from_millis(25));
234 buffer.clear();
235 }
236
237 previous = ascii;
238 }
239
240 result
241}