Skip to content

Commit 1d518b7

Browse files
committed
Faster recursive solution
1 parent 0834bd1 commit 1d518b7

File tree

2 files changed

+15
-17
lines changed

2 files changed

+15
-17
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ Performance is reasonable even on older hardware, for example a 2011 MacBook Pro
8888
| 14 | [Restroom Redoubt](https://adventofcode.com/2024/day/14) | [Source](src/year2024/day14.rs) | 74 |
8989
| 15 | [Warehouse Woes](https://adventofcode.com/2024/day/15) | [Source](src/year2024/day15.rs) | 303 |
9090
| 16 | [Reindeer Maze](https://adventofcode.com/2024/day/16) | [Source](src/year2024/day16.rs) | 390 |
91-
| 17 | [Chronospatial Computer](https://adventofcode.com/2024/day/17) | [Source](src/year2024/day17.rs) | 6 |
91+
| 17 | [Chronospatial Computer](https://adventofcode.com/2024/day/17) | [Source](src/year2024/day17.rs) | 2 |
9292

9393
## 2023
9494

src/year2024/day17.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
//!
3030
//! [`Intcode`]: crate::year2019::intcode
3131
use crate::util::parse::*;
32+
use std::ops::ControlFlow;
3233

3334
pub fn parse(input: &str) -> Vec<u64> {
3435
input.iter_unsigned().collect()
@@ -51,28 +52,25 @@ pub fn part1(input: &[u64]) -> String {
5152

5253
pub fn part2(input: &[u64]) -> u64 {
5354
// Start with known final value of `a`.
54-
let mut todo = vec![0];
55+
helper(input, input.len() - 1, 0).break_value().unwrap()
56+
}
5557

56-
for &valid in input.iter().skip(3).rev() {
57-
let mut next = Vec::new();
58+
fn helper(program: &[u64], index: usize, a: u64) -> ControlFlow<u64> {
59+
if index == 2 {
60+
return ControlFlow::Break(a);
61+
}
5862

59-
// Try all 8 combination of lower 3 bits for each possible valid value.
60-
for i in todo {
61-
for j in 0..8 {
62-
let a = (i << 3) | j;
63-
let mut computer = Computer::new(input, a);
63+
// Try all 8 combination of lower 3 bits.
64+
for i in 0..8 {
65+
let next_a = (a << 3) | i;
66+
let out = Computer::new(program, next_a).run().unwrap();
6467

65-
if computer.run().is_some_and(|out| out == valid) {
66-
next.push(a);
67-
}
68-
}
68+
if out == program[index] {
69+
helper(program, index - 1, next_a)?;
6970
}
70-
71-
todo = next;
7271
}
7372

74-
// Lowest possible initial value.
75-
todo[0]
73+
ControlFlow::Continue(())
7674
}
7775

7876
struct Computer<'a> {

0 commit comments

Comments
 (0)