Published
Edited
Dec 11, 2021
5 stars
Insert cell
Insert cell
Insert cell
part2 = {
let state = map;
let n = 0;
while (++n) {
state = step(state);
if (state.flashed.size === state.size) break;
}
return n;
}
Insert cell
part1 = {
let state = map;
let flashed = 0;
for (let n = 0; n < 100; n++) {
state = step(state);
flashed += state.flashed.size;
}
return flashed;
}
Insert cell
step = (map) => {
const next = new d3.InternMap([], JSON.stringify);
next.flashed = new d3.InternSet([], JSON.stringify);

for (const [[x, y], e] of map.entries()) next.set([x, y], e + 1);

let toFlash = new d3.InternSet(
d3.filter(next.keys(), (p) => next.get(p) > 9),
JSON.stringify
);
while (toFlash.size) {
const changed = new d3.InternSet([], JSON.stringify);
for (const p of toFlash) {
next.flashed.add(p);
for (const n of neighbors(p)) {
next.set(n, next.get(n) + 1);
changed.add(n);
}
}
toFlash = new d3.InternSet(
d3.filter(changed, (p) => !next.flashed.has(p) && next.get(p) > 9),
JSON.stringify
);
}

for (const p of next.flashed) next.set(p, 0);
return next;
}
Insert cell
function* neighbors([x, y]) {
for (const dx of [-1, 0, 1])
for (const dy of [-1, 0, 1])
if (!(dx === 0 && dy === 0) && map.has([x + dx, y + dy]))
yield [x + dx, y + dy];
}
Insert cell
map = {
const map = new d3.InternMap([], JSON.stringify);
for (let y = 0; y < data.length; y++)
for (let x = 0; x < data[y].length; x++)
map.set([x, y], data[y][x]);
return map;
}
Insert cell
data = (which === "test" ? test : which === "test2" ? test2 : input)
.trim()
.split("\n")
.map((l) => l.split("").map(Number))
Insert cell
Insert cell
test2 = `11111
19991
19191
19991
11111`
Insert cell
test = `5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526`
Insert cell
input = `7222221271
6463754232
3373484684
4674461265
1187834788
1175316351
8211411846
4657828333
5286325337
5771324832`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more