1
1
use crate :: solutions:: Solution ;
2
2
use itertools:: Itertools ;
3
+ use std:: collections:: { HashMap , HashSet } ;
3
4
4
5
pub struct Day22 ;
5
6
7
+ const SECRET_COUNT : usize = 2000 ;
8
+
6
9
impl Solution for Day22 {
7
10
fn part_one ( & self , input : & str ) -> String {
8
11
input
9
12
. lines ( )
10
13
. map ( |line| {
11
14
let initial: usize = line. parse ( ) . unwrap ( ) ;
12
- let secrets = self . next_secrets ( initial, 2000 ) ;
15
+ let secrets = self . next_secrets ( initial, SECRET_COUNT ) ;
13
16
14
17
* secrets. last ( ) . unwrap ( )
15
18
} )
@@ -18,18 +21,33 @@ impl Solution for Day22 {
18
21
}
19
22
20
23
fn part_two ( & self , input : & str ) -> String {
21
- let _diffs: Vec < Vec < i8 > > = input
22
- . lines ( )
23
- . map ( |line| {
24
- let initial: usize = line. parse ( ) . unwrap ( ) ;
25
- let secrets = self . next_secrets ( initial, 2000 ) ;
26
- let prices = self . prices ( secrets) ;
24
+ let mut map: HashMap < [ i8 ; 4 ] , usize > = HashMap :: new ( ) ;
27
25
28
- self . diffs ( prices)
29
- } )
30
- . collect ( ) ;
26
+ input. lines ( ) . for_each ( |line| {
27
+ let mut seen_map: HashSet < [ i8 ; 4 ] > = HashSet :: new ( ) ;
28
+
29
+ let initial: usize = line. parse ( ) . unwrap ( ) ;
30
+ let secrets = self . next_secrets ( initial, SECRET_COUNT ) ;
31
+ let prices = self . prices ( secrets) ;
32
+ let diffs = self . diffs ( & prices) ;
33
+
34
+ assert_eq ! ( SECRET_COUNT , diffs. len( ) ) ;
35
+
36
+ for i in 4 ..=diffs. len ( ) {
37
+ let key = [ diffs[ i - 4 ] , diffs[ i - 3 ] , diffs[ i - 2 ] , diffs[ i - 1 ] ] ;
38
+
39
+ if seen_map. contains ( & key) {
40
+ continue ;
41
+ }
42
+
43
+ * map. entry ( key) . or_insert ( 0 ) += prices[ i] as usize ;
44
+ seen_map. insert ( key) ;
45
+ }
46
+ } ) ;
47
+
48
+ let max = map. iter ( ) . max_by_key ( |( _, & v) | v) . unwrap ( ) ;
31
49
32
- String :: from ( "0" )
50
+ max . 1 . to_string ( )
33
51
}
34
52
}
35
53
@@ -57,7 +75,7 @@ impl Day22 {
57
75
secrets. iter ( ) . map ( |secret| ( secret % 10 ) as i8 ) . collect ( )
58
76
}
59
77
60
- fn diffs ( & self , secrets : Vec < i8 > ) -> Vec < i8 > {
78
+ fn diffs ( & self , secrets : & [ i8 ] ) -> Vec < i8 > {
61
79
secrets. iter ( ) . tuple_windows ( ) . map ( |( a, b) | b - a) . collect ( )
62
80
}
63
81
}
@@ -83,7 +101,6 @@ mod tests {
83
101
2024"# ;
84
102
85
103
#[ test]
86
- #[ ignore]
87
104
fn part_two_example ( ) {
88
105
assert_eq ! ( "23" , Day22 . part_two( PART_TWO_EXAMPLE ) ) ;
89
106
}
@@ -113,7 +130,7 @@ mod tests {
113
130
let prices = Day22 . prices ( secrets) ;
114
131
assert_eq ! ( vec![ 3 , 0 , 6 , 5 , 4 , 4 , 6 , 4 , 4 , 2 ] , prices) ;
115
132
116
- let diffs = Day22 . diffs ( prices) ;
133
+ let diffs = Day22 . diffs ( & prices) ;
117
134
assert_eq ! ( vec![ -3 , 6 , -1 , -1 , 0 , 2 , -2 , 0 , -2 ] , diffs) ;
118
135
}
119
136
}
0 commit comments