-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.ts
63 lines (55 loc) · 1.74 KB
/
part2.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
import * as fs from 'fs';
const input = fs.readFileSync('input', 'utf8').split('\n').map((line => line.split('')));
const startY = input.findIndex(line => line.includes('^'));
const startX = input[startY].indexOf('^');
const start = { x: startX, y: startY, direction: 'up' };
const STEP = {
up: { x: 0, y: -1, turnDirection: 'right' },
down: { x: 0, y: 1, turnDirection: 'left' },
left: { x: -1, y: 0, turnDirection: 'up' },
right: { x: 1, y: 0, turnDirection: 'down' },
};
input[start.y][start.x] = '.';
let current = { ...start };
const visited = new Set<string>();
while (input[current.y]?.[current.x]) {
const next = { ...current };
while (input[next.y]?.[next.x] === '.') {
visited.add(`${next.x},${next.y}`);
next.x += STEP[current.direction].x;
next.y += STEP[current.direction].y;
}
if (input[next.y]?.[next.x] === '#') {
next.x -= STEP[current.direction].x;
next.y -= STEP[current.direction].y;
next.direction = STEP[current.direction].turnDirection;
}
current = next;
}
let result = 0;
visited.forEach(pos => {
const [x, y] = pos.split(",").map(Number);
const map = input.map(row => [...row]);
map[y][x] = "#";
current = { ...start };
const turns = new Set<string>();
while (map[current.y]?.[current.x]) {
const next = { ...current };
while (map[next.y]?.[next.x] === ".") {
next.x += STEP[current.direction].x;
next.y += STEP[current.direction].y;
}
if (map[next.y]?.[next.x] === "#") {
next.x -= STEP[current.direction].x;
next.y -= STEP[current.direction].y;
next.direction = STEP[current.direction].turnDirection;
if (turns.has(`${next.x},${next.y},${next.direction}`)) {
result++;
break;
}
turns.add(`${next.x},${next.y},${next.direction}`);
}
current = next;
}
});
console.log(result);