-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.js
53 lines (46 loc) · 1002 Bytes
/
part1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString();
const grid = [];
input.split("\n").forEach((line) => grid.push(line.split("")));
const target = "XMAS";
let result = 0;
const directions = [
[-1, -1],
[0, -1],
[1, -1],
[-1, 0],
[1, 0],
[-1, 1],
[0, 1],
[1, 1],
];
// Search occurrences
function search(x, y, dx, dy, currentIndex) {
if (currentIndex === target.length) {
result += 1;
return;
}
const newX = x + dx;
const newY = y + dy;
if (
newX >= 0 &&
newY >= 0 &&
newX < grid[0].length &&
newY < grid.length &&
grid[newY][newX] === target[currentIndex]
) {
search(newX, newY, dx, dy, currentIndex + 1);
}
}
for (let y = 0; y < grid.length; y++) {
for (let x = 0; x < grid[0].length; x++) {
if (grid[y][x] === target[0]) {
for (const [dx, dy] of directions) {
search(x, y, dx, dy, 1);
}
}
}
}
console.log(result);