@@ -6,8 +6,8 @@ pub struct Day06;
66
77impl Solution for Day06 {
88 fn part_one ( & self , input : & str ) -> String {
9- let ( numbers, operations) = self . parse ( input) ;
10- let column_count = numbers . first ( ) . unwrap ( ) . len ( ) ;
9+ let ( numbers, operations) = self . parse_part_one ( input) ;
10+ let column_count = operations . len ( ) ;
1111
1212 ( 0 ..column_count)
1313 . map ( |column| {
@@ -23,13 +23,28 @@ impl Solution for Day06 {
2323 . to_string ( )
2424 }
2525
26- fn part_two ( & self , _input : & str ) -> String {
27- String :: from ( "0" )
26+ fn part_two ( & self , input : & str ) -> String {
27+ let ( numbers, operations) = self . parse_part_two ( input) ;
28+
29+ operations
30+ . iter ( )
31+ . rev ( )
32+ . enumerate ( )
33+ . map ( |( column, operation) | {
34+ let numbers_in_column = numbers. get ( column) . unwrap ( ) ;
35+
36+ match operation {
37+ Operation :: Add => numbers_in_column. iter ( ) . sum :: < u64 > ( ) ,
38+ Operation :: Multiply => numbers_in_column. iter ( ) . product ( ) ,
39+ }
40+ } )
41+ . sum :: < u64 > ( )
42+ . to_string ( )
2843 }
2944}
3045
3146impl Day06 {
32- fn parse ( & self , input : & str ) -> ( Vec < Vec < u64 > > , Vec < Operation > ) {
47+ fn parse_part_one ( & self , input : & str ) -> ( Vec < Vec < u64 > > , Vec < Operation > ) {
3348 let mut lines = input. lines ( ) . collect_vec ( ) ;
3449 let operations_str = lines. pop ( ) . unwrap ( ) ;
3550
@@ -49,6 +64,40 @@ impl Day06 {
4964
5065 ( numbers, operations)
5166 }
67+
68+ fn parse_part_two ( & self , input : & str ) -> ( Vec < Vec < u64 > > , Vec < Operation > ) {
69+ let mut lines = input. lines ( ) . collect_vec ( ) ;
70+ let operations_str = lines. pop ( ) . unwrap ( ) ;
71+ let operations = operations_str
72+ . split_whitespace ( )
73+ . map ( |x| x. parse :: < Operation > ( ) . unwrap ( ) )
74+ . collect_vec ( ) ;
75+
76+ let column_width = operations_str. len ( ) ;
77+
78+ let chunks = ( 0 ..column_width)
79+ . rev ( )
80+ . map ( |column| {
81+ lines
82+ . iter ( )
83+ . filter_map ( |line| line. chars ( ) . nth ( column) )
84+ . filter ( |ch| !ch. is_whitespace ( ) )
85+ . join ( "" )
86+ . parse :: < u64 > ( )
87+ } )
88+ . chunk_by ( |x| x. is_err ( ) ) ;
89+
90+ let mut groups = Vec :: new ( ) ;
91+ for ( _, rest) in & chunks {
92+ let numbers = rest. flatten ( ) . collect_vec ( ) ;
93+
94+ if !numbers. is_empty ( ) {
95+ groups. push ( numbers) ;
96+ }
97+ }
98+
99+ ( groups, operations)
100+ }
52101}
53102
54103#[ derive( Debug ) ]
@@ -83,4 +132,9 @@ mod tests {
83132 fn part_one_example_test ( ) {
84133 assert_eq ! ( "4277556" , Day06 . part_one( EXAMPLE ) ) ;
85134 }
135+
136+ #[ test]
137+ fn part_two_example_test ( ) {
138+ assert_eq ! ( "3263827" , Day06 . part_two( EXAMPLE ) ) ;
139+ }
86140}
0 commit comments