29
29
//!
30
30
//! [`Intcode`]: crate::year2019::intcode
31
31
use crate :: util:: parse:: * ;
32
+ use std:: ops:: ControlFlow ;
32
33
33
34
pub fn parse ( input : & str ) -> Vec < u64 > {
34
35
input. iter_unsigned ( ) . collect ( )
@@ -51,28 +52,25 @@ pub fn part1(input: &[u64]) -> String {
51
52
52
53
pub fn part2 ( input : & [ u64 ] ) -> u64 {
53
54
// Start with known final value of `a`.
54
- let mut todo = vec ! [ 0 ] ;
55
+ helper ( input, input. len ( ) - 1 , 0 ) . break_value ( ) . unwrap ( )
56
+ }
55
57
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
+ }
58
62
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 ( ) ;
64
67
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) ?;
69
70
}
70
-
71
- todo = next;
72
71
}
73
72
74
- // Lowest possible initial value.
75
- todo[ 0 ]
73
+ ControlFlow :: Continue ( ( ) )
76
74
}
77
75
78
76
struct Computer < ' a > {
0 commit comments