Skip to content

Commit d4f6841

Browse files
committed
Add solution for day 4 - part 2
1 parent 3ea2a60 commit d4f6841

File tree

1 file changed

+42
-4
lines changed

1 file changed

+42
-4
lines changed

src/day-4/index.ts

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { readFileFromCurrentDirectory } from '../utils/readFile.js';
33
const content = readFileFromCurrentDirectory();
44

55
const searchTerm = 'XMAS';
6-
let count = 0;
6+
let countPart1 = 0;
7+
let countPart2 = 0;
78

89
// Steps while searching in a direction: [row, col]
910
const searchDirections: { [key: string]: number[] } = {
@@ -28,12 +29,19 @@ for (let row = 0; row < grid.length; row++) {
2829
for (let col = 0; col < grid[row].length; col++) {
2930
// If current letter is first letter of search term, in our case 'X'
3031
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+
}
3240
}
3341
}
3442
}
3543

36-
function searchInAllDirections(col: number, row: number): number {
44+
function countInAllDirections(row: number, col: number): number {
3745
let termsFound = 0;
3846

3947
// Search in all directions
@@ -63,4 +71,34 @@ function searchInAllDirections(col: number, row: number): number {
6371
return termsFound;
6472
}
6573

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

Comments
 (0)