-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.js
64 lines (54 loc) · 1.22 KB
/
part2.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
54
55
56
57
58
59
60
61
62
63
64
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 = "MAS";
let targetOccurences = [];
const directions = [
[-1, -1],
[1, -1],
[-1, 1],
[1, 1],
];
// Search occurrences
function search(x, y, dx, dy, currentIndex) {
if (currentIndex === target.length) {
targetOccurences.push([x - dx, y - dy]);
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);
}
}
}
}
const parsed = [];
let result = 0;
targetOccurences.forEach((t) => {
let found = false;
parsed.forEach((p) => {
if (p[0] == t[0] && p[1] == t[1] && !found) {
result++;
found = true;
}
});
if (!found) parsed.push(t);
});
console.log(result);