@@ -3,7 +3,8 @@ import { readFileFromCurrentDirectory } from '../utils/readFile.js';
3
3
const content = readFileFromCurrentDirectory ( ) ;
4
4
5
5
const searchTerm = 'XMAS' ;
6
- let count = 0 ;
6
+ let countPart1 = 0 ;
7
+ let countPart2 = 0 ;
7
8
8
9
// Steps while searching in a direction: [row, col]
9
10
const searchDirections : { [ key : string ] : number [ ] } = {
@@ -28,12 +29,19 @@ for (let row = 0; row < grid.length; row++) {
28
29
for ( let col = 0 ; col < grid [ row ] . length ; col ++ ) {
29
30
// If current letter is first letter of search term, in our case 'X'
30
31
if ( grid [ row ] [ col ] === searchTerm [ 0 ] ) {
31
- count += ( searchInAllDirections ( col , row ) ) ;
32
+ countPart1 += countInAllDirections ( row , col ) ;
33
+ }
34
+
35
+ // If current letter is 'A' we check for X pattern
36
+ if ( grid [ row ] [ col ] === 'A' ) {
37
+ if ( checkPattern ( row , col ) ) {
38
+ countPart2 ++ ;
39
+ }
32
40
}
33
41
}
34
42
}
35
43
36
- function searchInAllDirections ( col : number , row : number ) : number {
44
+ function countInAllDirections ( row : number , col : number ) : number {
37
45
let termsFound = 0 ;
38
46
39
47
// Search in all directions
@@ -63,4 +71,34 @@ function searchInAllDirections(col: number, row: number): number {
63
71
return termsFound ;
64
72
}
65
73
66
- console . log ( 'Part 1: ' + count ) ;
74
+ function checkPattern ( row : number , col : number ) : boolean {
75
+ const searchTerms = [ 'MAS' , 'SAM' ] ;
76
+ const center = grid [ row ] [ col ] ;
77
+
78
+ const topleft = grid [ row - 1 ] ?. [ col - 1 ] ;
79
+ const bottomright = grid [ row + 1 ] ?. [ col + 1 ] ;
80
+
81
+ const topright = grid [ row - 1 ] ?. [ col + 1 ] ;
82
+ const bottomleft = grid [ row + 1 ] ?. [ col - 1 ] ;
83
+
84
+ const diagonal1 = [
85
+ topleft ,
86
+ center ,
87
+ bottomright
88
+ ] . join ( '' ) ;
89
+
90
+ const diagonal2 = [
91
+ topright ,
92
+ center ,
93
+ bottomleft
94
+ ] . join ( '' ) ;
95
+
96
+ if ( searchTerms . includes ( diagonal1 ) && searchTerms . includes ( diagonal2 ) ) {
97
+ return true ;
98
+ }
99
+
100
+ return false ;
101
+ }
102
+
103
+ console . log ( 'Part 1: ' + countPart1 ) ;
104
+ console . log ( 'Part 2: ' + countPart2 ) ;
0 commit comments