-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha.test.ts
89 lines (77 loc) · 2.55 KB
/
a.test.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { expect, test } from "bun:test";
function toKey([r, c, dr, dc]: [number, number, number, number]): string {
return `${r},${c},${dr},${dc}`;
}
function solution(input: string) {
const grid = input.split("\n");
const start: [number, number, number, number] = [0, -1, 0, 1];
const queue = [start];
const visited = new Set<string>();
while (queue.length > 0) {
const current = queue.shift();
if (!current) throw new Error("Unexpected value");
let [r, c, dr, dc] = current;
r += dr;
c += dc;
if (r < 0 || r >= grid.length || c < 0 || c >= grid[r].length) continue;
const ch = grid[r][c];
const key = toKey([r, c, dr, dc]);
if (ch === "." || (ch === "-" && dc !== 0) || (ch === "|" && dr !== 0)) {
if (!visited.has(key)) {
visited.add(key);
queue.push([r, c, dr, dc]);
}
} else if (ch === "/") {
[dr, dc] = [-dc, -dr];
if (!visited.has(key)) {
visited.add(key);
queue.push([r, c, dr, dc]);
}
} else if (ch === "\\") {
[dr, dc] = [dc, dr];
const key = toKey([r, c, dr, dc]);
if (!visited.has(key)) {
visited.add(key);
queue.push([r, c, dr, dc]);
}
} else {
const dirs =
ch === "|"
? [
[-1, 0],
[1, 0],
]
: [
[0, 1],
[0, -1],
];
for (const [dr, dc] of dirs) {
const key = toKey([r, c, dr, dc]);
if (!visited.has(key)) {
visited.add(key);
queue.push([r, c, dr, dc]);
}
}
}
}
const energized = new Set<string>();
for (const key of visited) {
const [r, c] = key.split(",").map(Number);
energized.add(`${r},${c}`);
}
return energized.size;
}
test("example", async () => {
const file = Bun.file(`${import.meta.dir}/example.txt`);
const input = await file.text();
const actual = solution(input);
const expected = 46;
expect(actual).toBe(expected);
});
test("puzzle input", async () => {
const file = Bun.file(`${import.meta.dir}/input.txt`);
const input = await file.text();
const actual = solution(input);
const expected = 8901;
expect(actual).toBe(expected);
});