@@ -6,40 +6,67 @@ impl Solution for Day08 {
66 fn part_one ( & self , input : & str ) -> String {
77 input
88 . lines ( )
9- . map ( |l| {
10- let mut i: usize = 1 ;
11- let len = l. len ( ) ;
12- let mut characters: usize = 0 ;
13-
14- loop {
15- if i == len - 1 {
16- break ;
17- }
18-
19- if l. chars ( ) . nth ( i) . unwrap ( ) == '\\' {
20- if l. chars ( ) . nth ( i + 1 ) . unwrap ( ) == 'x' {
21- i += 3 ;
22- } else {
23- i += 1 ;
24- }
25- }
26-
27- characters += 1 ;
9+ . map ( |word| {
10+ let result = Self :: process ( word) ;
2811
29- i += 1 ;
30- }
12+ result. code_length - result. memory_length
13+ } )
14+ . sum :: < usize > ( )
15+ . to_string ( )
16+ }
3117
32- len - characters
18+ fn part_two ( & self , input : & str ) -> String {
19+ input
20+ . lines ( )
21+ . map ( |word| {
22+ let encoded_string = format ! ( "\" {}\" " , word. escape_debug( ) ) ;
23+
24+ let original = Self :: process ( word) ;
25+ let encoded = Self :: process ( & encoded_string) ;
26+
27+ encoded. code_length - original. code_length
3328 } )
3429 . sum :: < usize > ( )
3530 . to_string ( )
3631 }
32+ }
33+
34+ impl Day08 {
35+ fn process ( word : & str ) -> Result {
36+ let mut i: usize = 1 ;
37+ let len = word. len ( ) ;
38+ let mut memory: usize = 0 ;
3739
38- fn part_two ( & self , _input : & str ) -> String {
39- String :: from ( "0" )
40+ loop {
41+ if i == len - 1 {
42+ break ;
43+ }
44+
45+ if word. chars ( ) . nth ( i) . unwrap ( ) == '\\' {
46+ if word. chars ( ) . nth ( i + 1 ) . unwrap ( ) == 'x' {
47+ i += 3 ;
48+ } else {
49+ i += 1 ;
50+ }
51+ }
52+
53+ memory += 1 ;
54+
55+ i += 1 ;
56+ }
57+
58+ Result {
59+ code_length : len,
60+ memory_length : memory,
61+ }
4062 }
4163}
4264
65+ struct Result {
66+ code_length : usize ,
67+ memory_length : usize ,
68+ }
69+
4370#[ cfg( test) ]
4471mod tests {
4572 use super :: * ;
@@ -51,4 +78,12 @@ mod tests {
5178 assert_eq ! ( "3" , Day08 . part_one( "\" aaa\\ \" aaa\" " ) ) ;
5279 assert_eq ! ( "5" , Day08 . part_one( "\" \\ x27\" " ) ) ;
5380 }
81+
82+ #[ test]
83+ fn part_two_example_test ( ) {
84+ assert_eq ! ( "4" , Day08 . part_two( "\" \" " ) ) ;
85+ assert_eq ! ( "4" , Day08 . part_two( "\" abc\" " ) ) ;
86+ assert_eq ! ( "6" , Day08 . part_two( "\" aaa\\ \" aaa\" " ) ) ;
87+ assert_eq ! ( "5" , Day08 . part_two( "\" \\ x27\" " ) ) ;
88+ }
5489}
0 commit comments