@@ -6,8 +6,22 @@ use std::str::FromStr;
66pub struct Day09 ;
77
88impl Solution for Day09 {
9- fn part_one ( & self , _input : & str ) -> String {
10- String :: from ( '0' )
9+ fn part_one ( & self , input : & str ) -> String {
10+ let mut disk_map = DiskMap :: from_str ( input) . unwrap ( ) ;
11+
12+ loop {
13+ let last_digit_index = disk_map. blocks . iter ( ) . rposition ( |v| v. is_some ( ) ) . unwrap ( ) ;
14+ let first_empty_index = disk_map. blocks . iter ( ) . position ( |v| v. is_none ( ) ) . unwrap ( ) ;
15+
16+ if first_empty_index > last_digit_index {
17+ break ;
18+ }
19+
20+ disk_map. blocks [ first_empty_index] = Some ( disk_map. blocks [ last_digit_index] . unwrap ( ) ) ;
21+ disk_map. blocks [ last_digit_index] = None ;
22+ }
23+
24+ disk_map. checksum ( ) . to_string ( )
1125 }
1226
1327 fn part_two ( & self , _input : & str ) -> String {
@@ -19,17 +33,32 @@ struct DiskMap {
1933 blocks : Vec < Option < usize > > ,
2034}
2135
36+ impl DiskMap {
37+ fn checksum ( & self ) -> usize {
38+ self . blocks
39+ . clone ( )
40+ . into_iter ( )
41+ . flatten ( )
42+ . enumerate ( )
43+ . fold ( 0 , |acc, ( i, id) | acc + i * id)
44+ }
45+ }
46+
2247impl FromStr for DiskMap {
2348 type Err = String ;
2449
2550 fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
2651 let mut current_id = 0 ;
2752
2853 let test: Vec < Option < usize > > = s
54+ . trim ( )
2955 . chars ( )
3056 . enumerate ( )
3157 . flat_map ( |( i, c) | {
32- let times: usize = c. to_string ( ) . parse ( ) . unwrap ( ) ;
58+ let times: usize = c
59+ . to_string ( )
60+ . parse ( )
61+ . unwrap_or_else ( |_| panic ! ( "cannot parse char to usize: '{}'" , c) ) ;
3362
3463 let value: Option < usize > = match i % 2 == 0 {
3564 true => {
@@ -71,11 +100,11 @@ mod tests {
71100 use crate :: solutions:: Solution ;
72101 use std:: str:: FromStr ;
73102
74- const EXAMPLE : & str = r#""# ;
103+ const EXAMPLE : & str = "2333133121414131402" ;
75104
76105 #[ test]
77106 fn part_one_example_test ( ) {
78- assert_eq ! ( "0 " , Day09 . part_one( EXAMPLE ) ) ;
107+ assert_eq ! ( "1928 " , Day09 . part_one( EXAMPLE ) ) ;
79108 }
80109
81110 #[ test]
0 commit comments