@@ -3,24 +3,79 @@ use crate::solutions::Solution;
33pub struct Day22 ;
44
55impl Solution for Day22 {
6- fn part_one ( & self , _input : & str ) -> String {
7- String :: from ( "0" )
6+ fn part_one ( & self , input : & str ) -> String {
7+ input
8+ . lines ( )
9+ . map ( |line| {
10+ let initial: usize = line. parse ( ) . unwrap ( ) ;
11+ let secrets = self . next_secrets ( initial, 2000 ) ;
12+
13+ * secrets. last ( ) . unwrap ( )
14+ } )
15+ . sum :: < usize > ( )
16+ . to_string ( )
817 }
918
1019 fn part_two ( & self , _input : & str ) -> String {
1120 String :: from ( "0" )
1221 }
1322}
1423
24+ impl Day22 {
25+ fn next_secrets ( & self , initial : usize , number_of_secrets : usize ) -> Vec < usize > {
26+ let mut secret = initial;
27+ let mut next_secrets = Vec :: new ( ) ;
28+
29+ for _ in 0 ..number_of_secrets {
30+ let tmp = secret * 64 ;
31+ secret ^= tmp;
32+ secret %= 16777216 ;
33+
34+ let tmp = secret / 32 ;
35+ secret ^= tmp;
36+ secret %= 16777216 ;
37+
38+ let tmp = secret * 2048 ;
39+ secret ^= tmp;
40+ secret %= 16777216 ;
41+
42+ next_secrets. push ( secret) ;
43+ }
44+
45+ next_secrets
46+ }
47+ }
48+
1549#[ cfg( test) ]
1650mod tests {
1751 use crate :: solutions:: year2024:: day22:: Day22 ;
1852 use crate :: solutions:: Solution ;
1953
20- const EXAMPLE : & str = r#""# ;
54+ const EXAMPLE : & str = r#"1
55+ 10
56+ 100
57+ 2024"# ;
2158
2259 #[ test]
2360 fn part_one_example ( ) {
24- assert_eq ! ( "0" , Day22 . part_one( EXAMPLE ) ) ;
61+ assert_eq ! ( "37327623" , Day22 . part_one( EXAMPLE ) ) ;
62+ }
63+
64+ #[ test]
65+ fn next_secrets ( ) {
66+ let tmp = Day22 . next_secrets ( 123 , 10 ) ;
67+ let mut result = tmp. iter ( ) ;
68+
69+ assert_eq ! ( Some ( & 15887950 ) , result. next( ) ) ;
70+ assert_eq ! ( Some ( & 16495136 ) , result. next( ) ) ;
71+ assert_eq ! ( Some ( & 527345 ) , result. next( ) ) ;
72+ assert_eq ! ( Some ( & 704524 ) , result. next( ) ) ;
73+ assert_eq ! ( Some ( & 1553684 ) , result. next( ) ) ;
74+ assert_eq ! ( Some ( & 12683156 ) , result. next( ) ) ;
75+ assert_eq ! ( Some ( & 11100544 ) , result. next( ) ) ;
76+ assert_eq ! ( Some ( & 12249484 ) , result. next( ) ) ;
77+ assert_eq ! ( Some ( & 7753432 ) , result. next( ) ) ;
78+ assert_eq ! ( Some ( & 5908254 ) , result. next( ) ) ;
79+ assert_eq ! ( None , result. next( ) ) ;
2580 }
2681}
0 commit comments