-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpart-two.ts
68 lines (58 loc) · 1.34 KB
/
part-two.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
import { input, type Grid } from './input';
const N = 'N';
const NE = 'NE';
const E = 'E';
const SE = 'SE';
const S = 'S';
const SW = 'SW';
const W = 'W';
const NW = 'NW';
type Directions =
| typeof N
| typeof NE
| typeof E
| typeof SE
| typeof S
| typeof SW
| typeof W
| typeof NW;
const vectors = new Map<Directions, [number, number]>([
[N, [-1, 0]],
[NE, [-1, 1]],
[E, [0, 1]],
[SE, [1, 1]],
[S, [1, 0]],
[SW, [1, -1]],
[W, [0, -1]],
[NW, [-1, -1]],
]);
function get(grid: Grid, x: number, y: number, delta?: [number, number]): string | undefined {
return grid[y + (delta?.[1] ?? 0)]?.[x + (delta?.[0] ?? 0)];
}
function isMatch(grid: Grid, x: number, y: number): boolean {
const cellNE = get(grid, x, y, vectors.get(NE));
const cellSW = get(grid, x, y, vectors.get(SW));
const cellNW = get(grid, x, y, vectors.get(NW));
const cellSE = get(grid, x, y, vectors.get(SE));
// prettier-ignore
return (
[cellNE, cellSW].sort().join('') === 'MS' &&
[cellNW, cellSE].sort().join('') === 'MS'
);
}
function countMatches(grid: Grid): number {
let matches = 0;
for (let y = 0; y < grid.length; y++) {
for (let x = 0; x < grid[y].length; x++) {
const cell = grid[y][x];
if (cell === 'A') {
if (isMatch(grid, x, y)) {
matches++;
}
}
}
}
return matches;
}
const answer = countMatches(input);
console.log(answer);