11use crate :: solutions:: Solution ;
2+ use itertools:: Itertools ;
3+ use std:: fmt:: { Display , Formatter } ;
4+ use std:: str:: FromStr ;
25
36pub struct Day09 ;
47
@@ -12,15 +15,78 @@ impl Solution for Day09 {
1215 }
1316}
1417
18+ struct DiskMap {
19+ blocks : Vec < Option < usize > > ,
20+ }
21+
22+ impl FromStr for DiskMap {
23+ type Err = String ;
24+
25+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
26+ let mut current_id = 0 ;
27+
28+ let test: Vec < Option < usize > > = s
29+ . chars ( )
30+ . enumerate ( )
31+ . flat_map ( |( i, c) | {
32+ let times: usize = c. to_string ( ) . parse ( ) . unwrap ( ) ;
33+
34+ let value: Option < usize > = match i % 2 == 0 {
35+ true => {
36+ let id = Some ( current_id) ;
37+
38+ current_id += 1 ;
39+
40+ id
41+ }
42+ false => None ,
43+ } ;
44+
45+ vec ! [ value; times]
46+ } )
47+ . collect ( ) ;
48+
49+ Ok ( Self { blocks : test } )
50+ }
51+ }
52+
53+ impl Display for DiskMap {
54+ fn fmt ( & self , f : & mut Formatter < ' _ > ) -> std:: fmt:: Result {
55+ let value = self
56+ . blocks
57+ . iter ( )
58+ . map ( |v| match v {
59+ None => '.' ,
60+ Some ( v) => ( v % 10 ) . to_string ( ) . chars ( ) . next ( ) . unwrap ( ) ,
61+ } )
62+ . join ( "" ) ;
63+
64+ write ! ( f, "{}" , value)
65+ }
66+ }
67+
1568#[ cfg( test) ]
1669mod tests {
17- use crate :: solutions:: year2024:: day09:: Day09 ;
70+ use crate :: solutions:: year2024:: day09:: { Day09 , DiskMap } ;
1871 use crate :: solutions:: Solution ;
72+ use std:: str:: FromStr ;
1973
2074 const EXAMPLE : & str = r#""# ;
2175
2276 #[ test]
2377 fn part_one_example_test ( ) {
2478 assert_eq ! ( "0" , Day09 . part_one( EXAMPLE ) ) ;
2579 }
80+
81+ #[ test]
82+ fn parse_test ( ) {
83+ let result = DiskMap :: from_str ( "12345" ) . unwrap ( ) ;
84+ assert_eq ! ( "0..111....22222" , result. to_string( ) ) ;
85+
86+ let result = DiskMap :: from_str ( "2333133121414131402" ) . unwrap ( ) ;
87+ assert_eq ! (
88+ "00...111...2...333.44.5555.6666.777.888899" ,
89+ result. to_string( )
90+ ) ;
91+ }
2692}
0 commit comments