1
1
advent_of_code:: solution!( 4 ) ;
2
2
3
- const DIRECTIONS : [ ( isize , isize ) ; 8 ] = [
3
+ const DIRECTIONS : [ ( i32 , i32 ) ; 8 ] = [
4
4
( 0 , 1 ) ,
5
5
( 1 , 0 ) ,
6
6
( 1 , 1 ) ,
@@ -11,57 +11,46 @@ const DIRECTIONS: [(isize, isize); 8] = [
11
11
( -1 , 1 ) ,
12
12
] ;
13
13
14
- fn count_xmas_occurrences ( grid : Vec < Vec < char > > , target : & str ) -> usize {
15
- let rows = grid. len ( ) ;
16
- let cols = grid. len ( ) ;
17
- let mut count = 0 ;
18
-
19
- for i in 0 ..rows {
20
- for j in 0 ..cols {
21
- for & ( dx, dy) in & DIRECTIONS {
22
- count += check_direction ( & grid, i, j, dx, dy, target) ;
14
+ fn count_xmas_occurrences ( grid : Vec < Vec < char > > , word : & str ) -> usize {
15
+ let mut result: u32 = 0 ;
16
+ let word_length: usize = word. chars ( ) . count ( ) ;
17
+
18
+ for y in 0 ..grid. len ( ) {
19
+ for x in 0 ..grid. len ( ) {
20
+ if grid[ y] [ x] == word. chars ( ) . next ( ) . unwrap ( ) {
21
+ for & d in & DIRECTIONS {
22
+ let mut found = true ;
23
+
24
+ for j in 1 ..word_length {
25
+ let nx = x as i32 + d. 0 * j as i32 ;
26
+ let ny = y as i32 + d. 1 * j as i32 ;
27
+
28
+ if nx < 0
29
+ || ny < 0
30
+ || nx >= grid[ 0 ] . len ( ) as i32
31
+ || ny >= grid. len ( ) as i32
32
+ || grid[ ny as usize ] [ nx as usize ] != word. chars ( ) . nth ( j) . unwrap ( )
33
+ {
34
+ found = false ; // If any character does not match, break
35
+ break ;
36
+ }
37
+ }
38
+
39
+ if found {
40
+ result += 1 ;
41
+ }
42
+ }
23
43
}
24
44
}
25
45
}
26
46
27
- count
47
+ result as usize
28
48
}
29
49
30
- fn check_direction (
31
- grid : & [ Vec < char > ] , //&Vec<Vec<char>>,
32
- start_x : usize ,
33
- start_y : usize ,
34
- dx : isize ,
35
- dy : isize ,
36
- target : & str ,
37
- ) -> usize {
38
- let mut x = start_x as isize ;
39
- let mut y = start_y as isize ;
40
- let target_len = target. len ( ) ;
41
- let mut chars = Vec :: new ( ) ;
42
-
43
- for _ in 0 ..target_len {
44
- // Check we are within table
45
- if x < 0 || y < 0 || x >= grid. len ( ) as isize || y >= grid[ 0 ] . len ( ) as isize {
46
- return 0 ;
47
- }
48
- chars. push ( grid[ x as usize ] [ y as usize ] ) ;
49
- x += dx;
50
- y += dy;
51
- }
52
-
53
- if chars. iter ( ) . collect :: < String > ( ) == target {
54
- return 1 ;
55
- }
56
-
57
- 0
58
- }
59
-
60
- pub fn part_one ( input : & str ) -> Option < u32 > {
50
+ pub fn part_one ( input : & str ) -> Option < usize > {
61
51
let chars = input. lines ( ) . map ( |line| line. chars ( ) . collect ( ) ) . collect ( ) ;
62
52
let result = count_xmas_occurrences ( chars, "XMAS" ) ;
63
-
64
- Some ( result as u32 )
53
+ Some ( result)
65
54
}
66
55
67
56
pub fn part_two ( input : & str ) -> Option < u32 > {
0 commit comments