Skip to content

Commit 8f07387

Browse files
committed
17th day
1 parent c9a53d8 commit 8f07387

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

data/examples/17.txt

Lines changed: 5 additions & 0 deletions
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

src/bin/17.rs

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
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+
let result_capacity = program_result.len() * 2;
30+
31+
let mut result = String::with_capacity(result_capacity);
32+
for x in program_result {
33+
result.push((b'0' + x) as char);
34+
result.push(',');
35+
}
36+
result.pop();
37+
38+
Some(result)
39+
}
40+
41+
pub fn part_two(input: &str) -> Option<u64> {
42+
let (_, program) = parse_data(input);
43+
44+
let mut result = u64::MAX;
45+
46+
let mut queue = vec![];
47+
queue.push((0, program.len() - 1));
48+
49+
while let Some((a, i)) = queue.pop() {
50+
let p_i = program[i] as u64;
51+
52+
for part_a in 0..=7 {
53+
let n_a = (a << 3) | (p_i ^ part_a ^ 5) << (part_a ^ 1) | part_a;
54+
55+
if i == 0 {
56+
if run_program(n_a) == program {
57+
result = result.min(n_a);
58+
}
59+
} else {
60+
if run_program(n_a) == program[i..] {
61+
queue.push((n_a, i - 1));
62+
}
63+
}
64+
}
65+
}
66+
67+
Some(result)
68+
}
69+
70+
#[cfg(test)]
71+
mod tests {
72+
use super::*;
73+
74+
#[test]
75+
fn test_part_one() {
76+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
77+
assert_eq!(result, Some(String::from("5,0,4,5")));
78+
}
79+
80+
#[test]
81+
fn test_part_two() {
82+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
83+
assert_eq!(result, Some(188468));
84+
}
85+
}

0 commit comments

Comments
 (0)