-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday16.js
43 lines (37 loc) · 1.7 KB
/
day16.js
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
import { asLines } from './util.js';
const layout = asLines('../input/day16.txt').map(line => line.split(''));
const traceLight = (layout, light, visited) => {
const {x, y, dx, dy} = light;
if (x < 0 || y < 0 || x >= layout[0].length || y >= layout.length) {
return []; // light has left the building
}
if (!visited.has(`${x},${y}`)) visited.set(`${x},${y}`, new Set());
if (visited.get(`${x},${y}`).has(`${dx},${dy}`)) return []; // light has looped
visited.get(`${x},${y}`).add(`${dx},${dy}`);
const current = layout[y][x];
let next = [{dx, dy}];
if (current === '/') next = [{dx: -dy, dy: -dx}];
if (current === '\\') next = [{dx: dy, dy: dx}];
if (current === '|' && dx !==0) next = [{dx: dy, dy: -1}, {dx: dy, dy: 1}];
if (current === '-' && dy !==0) next = [{dx: -1, dy: dx}, {dx: 1, dy: dx}];
return next.map(({dx, dy}) => ({x: x + dx, y: y + dy, dx, dy}));
}
const traceLights = (layout, lights) => {
const visited = new Map();
while (lights.length > 0) {
lights = lights.flatMap(light => traceLight(layout, light, visited));
}
return visited.size;
}
const energized = traceLights(layout, [{x: 0, y: 0, dx: 1, dy: 0}]);
console.log(`part1: ${energized}`);
let energized2 = 0;
for (let y = 0; y < layout.length; y++) {
energized2 = Math.max(energized2, traceLights(layout, [{x: 0, y, dx: 1, dy: 0}]));
energized2 = Math.max(energized2, traceLights(layout, [{x: layout[0].length - 1, y, dx: -1, dy: 0}]));
}
for (let x = 0; x < layout[0].length; x++) {
energized2 = Math.max(energized2, traceLights(layout, [{x, y: 0, dx: 0, dy: 1}]));
energized2 = Math.max(energized2, traceLights(layout, [{x, y: layout.length - 1, dx: 0, dy: -1}]));
}
console.log(`part2: ${energized2}`);