-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpart-two.js
More file actions
64 lines (52 loc) · 1.23 KB
/
part-two.js
File metadata and controls
64 lines (52 loc) · 1.23 KB
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
const { input } = require('./input');
const { InfiniteGrid } = require('./infinite-grid');
let grid = new InfiniteGrid({
load: input,
parseAs: Number,
});
function doFlashing(flashed) {
let new_flashes = [];
for (let id of flashed) {
let neighbors = grid.neighbors(...InfiniteGrid.toCoords(id), true);
for (let { coord, value } of neighbors.values()) {
let [x, y] = coord;
let new_value = value + 1;
// Only flash once when we are at 10 energy
if (new_value === 10) {
new_flashes.push(InfiniteGrid.toId(x, y));
}
grid.set(x, y, new_value);
}
}
return new_flashes;
}
let all_flashed = false;
let step = 0;
while (!all_flashed) {
let flashed = [];
for (let [id, value] of grid) {
let new_value = value + 1;
grid.grid.set(id, new_value);
if (value <= 9 && new_value > 9) {
flashed.push(id);
}
}
while (flashed.length > 0) {
flashed = doFlashing(flashed);
}
// Count and reset all flashed octos back to `0`
let total_flashed = 0;
for (let [id, value] of grid) {
if (value > 9) {
total_flashed++;
grid.grid.set(id, 0);
}
}
// The step is finished, increment
step++;
if (total_flashed === 100) {
// We can break our loop, we have our answer
all_flashed = true;
}
}
console.log(step);