-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
121 lines (109 loc) · 2.6 KB
/
index.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import run from "aocrunner";
type Point = [number, number];
const positionIndex = (x: number, y: number, width: number) => x + y * width;
const parseInput = (rawInput: string) => {
const frequencies = new Map<string, Point[]>();
const rows = rawInput.split("\n");
const width = rows[0].length;
for (let y = 0; y < rows.length; y++) {
for (let x = 0; x < rows[0].length; x++) {
const value = rows[y][x];
if (value !== ".") {
if (frequencies.has(value)) {
frequencies.get(value)!.push([x, y]);
} else {
frequencies.set(value, [[x, y]]);
}
}
}
}
return { frequencies, width, height: rows.length };
};
const part1 = (rawInput: string) => {
const { frequencies, width, height } = parseInput(rawInput);
const antinodes = new Set<number>();
for (const points of frequencies.values()) {
for (let i = 0; i < points.length; i++) {
for (let j = 0; j < points.length; j++) {
if (i === j) continue;
const [x1, y1] = points[i];
const [x2, y2] = points[j];
const x3 = 2 * x2 - x1;
const y3 = 2 * y2 - y1;
if (x3 >= 0 && y3 >= 0 && x3 < width && y3 < height) {
antinodes.add(positionIndex(x3, y3, width));
}
}
}
}
return antinodes.size;
};
const part2 = (rawInput: string) => {
const { frequencies, width, height } = parseInput(rawInput);
const antinodes = new Set<number>();
for (const points of frequencies.values()) {
for (let i = 0; i < points.length; i++) {
for (let j = 0; j < points.length; j++) {
if (i === j) continue;
const [x1, y1] = points[i];
const [x2, y2] = points[j];
let d = 0;
while (true) {
const x3 = x2 + d * (x2 - x1);
const y3 = y2 + d * (y2 - y1);
if (x3 >= 0 && y3 >= 0 && x3 < width && y3 < height) {
antinodes.add(positionIndex(x3, y3, width));
d++;
} else {
break;
}
}
}
}
}
return antinodes.size;
};
run({
part1: {
tests: [
{
input: `............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............`,
expected: 14,
},
],
solution: part1,
},
part2: {
tests: [
{
input: `............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............`,
expected: 34,
},
],
solution: part2,
},
trimTestInputs: true,
onlyTests: false,
});