-
Notifications
You must be signed in to change notification settings - Fork 5
/
day08.mjs
80 lines (71 loc) · 1.82 KB
/
day08.mjs
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
import { readFileSync } from "node:fs";
const lines = readFileSync("day08.txt", { encoding: "utf-8" }) // read day??.txt content
.replace(/\r/g, "") // remove all \r characters to avoid issues on Windows
.trim() // Remove starting/ending whitespace
.split("\n") // Split on newline
.map((line) => [...line].map(Number));
function setVisible(y, x, visible) {
visible.add(`${y}-${x}`);
}
function checkLine(y, x, dy, dx, map, visible) {
setVisible(y, x, visible);
let maximum = map[y][x];
// loop
while (true) {
y += dy;
x += dx;
if (y < 0 || y >= map.length || x < 0 || x >= map[y].length) {
break;
}
if (map[y][x] > maximum) {
maximum = map[y][x];
setVisible(y, x, visible);
}
}
}
function checkLine2(y, x, dy, dx, map) {
let visible = 0;
let maximum = map[y][x];
while (true) {
y += dy;
x += dx;
if (y < 0 || y >= map.length || x < 0 || x >= map[y].length) {
break;
}
visible++;
if (map[y][x] >= maximum) {
break;
}
}
return visible;
}
function part1() {
const visible = new Set();
// all columns
for (let i = 0; i < lines[0].length; i++) {
checkLine(0, i, 1, 0, lines, visible);
checkLine(lines.length - 1, i, -1, 0, lines, visible);
}
// all rows
for (let i = 0; i < lines.length; i++) {
checkLine(i, 0, 0, 1, lines, visible);
checkLine(i, lines[0].length - 1, 0, -1, lines, visible);
}
console.log(visible.size);
}
function part2() {
let max = 0;
for (let y = 0; y < lines.length; y++) {
for (let x = 0; x < lines[y].length; x++) {
const score =
checkLine2(y, x, -1, 0, lines) *
checkLine2(y, x, 1, 0, lines) *
checkLine2(y, x, 0, 1, lines) *
checkLine2(y, x, 0, -1, lines);
if (score > max) max = score;
}
}
console.log(max);
}
part1();
part2();