-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday6.ts
104 lines (85 loc) · 2.18 KB
/
day6.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { input } from './input';
const inputGrid = input.split('\n').map((r) => r.split(''));
function findStart(grid: string[][]) {
for (let i = 0; i < grid[0].length; i++) {
const row = grid[i];
for (let j = 0; j < row.length; j++) {
const c = row[j];
if (c === '^') {
return { x: i, y: j };
}
}
}
throw new Error('Failed to find start');
}
function getChar(grid: string[][], x: number, y: number) {
return grid[x]?.[y];
}
const direction = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
];
function part1(originalGrid: string[][]) {
const cands: [number, number][] = [];
const grid = structuredClone(originalGrid);
let result = 1;
let { x, y } = findStart(grid);
let dir = 0;
let c = getChar(grid, x, y);
while (c != null) {
let next = [x + direction[dir][0], y + direction[dir][1]];
const nextChar = getChar(grid, next[0], next[1]);
if (nextChar === '#') {
// rotate right
dir = (dir + 1) % 4;
continue;
}
if (c === '.') {
result++;
grid[x][y] = 'X';
cands.push([x, y]);
}
x = next[0];
y = next[1];
c = nextChar;
}
return { result, cands };
}
function part2(originalGrid: string[][], cands: [number, number][]) {
let result = 0;
const start = findStart(originalGrid);
const grid = structuredClone(originalGrid);
// try each candidate as an obstacle
for (let obs of cands) {
const visited = new Set<string>();
let { x, y } = start;
let dir = 0;
let c = getChar(grid, x, y);
while (c != null) {
let next = [x + direction[dir][0], y + direction[dir][1]];
const nextChar = getChar(grid, next[0], next[1]);
if (nextChar === '#' || (next[0] === obs[0] && next[1] === obs[1])) {
// rotate right
dir = (dir + 1) % 4;
continue;
}
if (c === '.') {
const key = `${x},${y},${dir}`;
if (visited.has(key)) {
result++;
break;
}
visited.add(key);
}
x = next[0];
y = next[1];
c = nextChar;
}
}
return result;
}
const { result: result1, cands } = part1(inputGrid);
console.log(result1);
console.log(part2(inputGrid, cands));