Skip to content

Commit d9dd7ad

Browse files
committed
17th day
1 parent c9a53d8 commit d9dd7ad

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

Diff for: data/examples/17.txt

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Register A: 729
2+
Register B: 0
3+
Register C: 0
4+
5+
Program: 0,3,5,5,3,0

Diff for: src/bin/17.rs

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
advent_of_code::solution!(17);
2+
3+
use advent_of_code::maneatingape::parse::*;
4+
5+
fn parse_data(input: &str) -> (u64, Vec<u8>) {
6+
let (left, right) = input.split_once("\n\n").unwrap();
7+
8+
(left.unsigned(), right.iter_unsigned().collect())
9+
}
10+
11+
fn run_program(a: u64) -> Vec<u8> {
12+
let mut result = vec![];
13+
14+
let mut a = a;
15+
while a > 0 {
16+
let b = (a ^ 1) & 7;
17+
result.push((((b ^ (a >> b)) ^ 4) & 7) as u8);
18+
19+
a >>= 3;
20+
}
21+
22+
result
23+
}
24+
25+
pub fn part_one(input: &str) -> Option<String> {
26+
let (a, _) = parse_data(input);
27+
28+
let program_result = run_program(a);
29+
30+
let mut result = String::with_capacity(program_result.len() * 2);
31+
for x in program_result {
32+
result.push((b'0' + x) as char);
33+
result.push(',');
34+
}
35+
result.pop();
36+
37+
Some(result)
38+
}
39+
40+
pub fn part_two(input: &str) -> Option<u64> {
41+
let (_, program) = parse_data(input);
42+
43+
let mut result = u64::MAX;
44+
45+
let mut queue = vec![];
46+
queue.push((0, program.len() - 1));
47+
48+
while let Some((a, i)) = queue.pop() {
49+
let p_i = program[i] as u64;
50+
51+
for part_a in 0..=7 {
52+
let n_a = (a << 3) | (p_i ^ part_a ^ 5) << (part_a ^ 1) | part_a;
53+
54+
if i > 0 && run_program(n_a) == program[i..] {
55+
queue.push((n_a, i - 1));
56+
continue;
57+
}
58+
59+
if i == 0 && run_program(n_a) == program {
60+
result = result.min(n_a);
61+
}
62+
}
63+
}
64+
65+
Some(result)
66+
}
67+
68+
#[cfg(test)]
69+
mod tests {
70+
use super::*;
71+
72+
#[test]
73+
fn test_part_one() {
74+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
75+
assert_eq!(result, Some(String::from("5,0,4,5")));
76+
}
77+
78+
#[test]
79+
fn test_part_two() {
80+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
81+
assert_eq!(result, Some(188468));
82+
}
83+
}

0 commit comments

Comments
 (0)