@@ -24,9 +24,7 @@ pub fn part_one(input: &str) -> Option<u32> {
2424 for i in 0 ..4 {
2525 let ( r, c) = ( row + ( i * dr) , col + ( i * dc) ) ;
2626 if r >= 0 && c >= 0 && r < m && c < n {
27- if xmas. chars ( ) . nth ( i as usize ) . unwrap ( )
28- != matrix[ r as usize ] [ c as usize ]
29- {
27+ if xmas. chars ( ) . nth ( i as usize ) . unwrap ( ) != matrix[ r as usize ] [ c as usize ] {
3028 continue ' outer;
3129 }
3230 } else {
@@ -51,7 +49,36 @@ pub fn part_one(input: &str) -> Option<u32> {
5149}
5250
5351pub fn part_two ( input : & str ) -> Option < u32 > {
54- None
52+ let matrix: Vec < Vec < char > > = input. lines ( ) . map ( |line| line. chars ( ) . collect ( ) ) . collect ( ) ;
53+ let m = matrix. len ( ) as i32 ;
54+ let n = matrix[ 0 ] . len ( ) as i32 ;
55+
56+ let valid = |c : char | -> bool {
57+ return c == 'M' || c == 'S' ;
58+ } ;
59+
60+ let check_pos = |row : usize , col : usize | -> bool {
61+ let center = matrix[ row] [ col] ;
62+ let a = matrix[ row - 1 ] [ col - 1 ] ;
63+ let b = matrix[ row + 1 ] [ col + 1 ] ;
64+ let c = matrix[ row + 1 ] [ col - 1 ] ;
65+ let d = matrix[ row - 1 ] [ col + 1 ] ;
66+ let primary = valid ( a) && valid ( b) && ( a != b) ;
67+ let secondary = valid ( c) && valid ( d) && ( c != d) ;
68+ return center == 'A' && primary && secondary;
69+ } ;
70+
71+ let mut count = 0 ;
72+
73+ for i in 1 ..m - 1 {
74+ for j in 1 ..n - 1 {
75+ if check_pos ( i as usize , j as usize ) {
76+ count += 1 ;
77+ }
78+ }
79+ }
80+
81+ Some ( count as u32 )
5582}
5683
5784#[ cfg( test) ]
@@ -66,7 +93,9 @@ mod tests {
6693
6794 #[ test]
6895 fn test_part_two ( ) {
69- let result = part_two ( & advent_of_code:: template:: read_file ( "examples" , DAY ) ) ;
70- assert_eq ! ( result, None ) ;
96+ let result = part_two ( & advent_of_code:: template:: read_file_part (
97+ "examples" , DAY , 2 ,
98+ ) ) ;
99+ assert_eq ! ( result, Some ( 9 ) ) ;
71100 }
72101}
0 commit comments