Public
Edited
Dec 25, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
initial = {
const state = new d3.InternSet([], String);
(which === "sample" ? sample : input)
.trim()
.split("\n")
.forEach((l, y) => {
[...l].forEach((c, x) => {
if (c === "#") state.add([x, y]);
});
});
return state;
}
Insert cell
directions = [
[([x, y]) => [-1, 0, 1].map((dx) => [x + dx, y - 1]), [0, -1]], // north
[([x, y]) => [-1, 0, 1].map((dx) => [x + dx, y + 1]), [0, +1]], // south
[([x, y]) => [-1, 0, 1].map((dy) => [x - 1, y + dy]), [-1, 0]], // west
[([x, y]) => [-1, 0, 1].map((dy) => [x + 1, y + dy]), [+1, 0]] // east
]
Insert cell
function* rotated(offset) {
for (let i = 0; i < directions.length; i++)
yield directions[(i + offset) % directions.length];
}
Insert cell
function* neighbors([x, y]) {
for (const nx of [x - 1, x, x + 1])
for (const ny of [y - 1, y, y + 1])
if (!(nx === x && ny === y)) yield [nx, ny];
}
Insert cell
propose = (p, i, elves) => {
if (d3.every(neighbors(p), (n) => !elves.has(n))) return p;
const [x, y] = p;
for (const [direction, [dx, dy]] of rotated(i))
if (!direction(p).some((n) => elves.has(n))) return [x + dx, y + dy];
return p;
}
Insert cell
Insert cell
function* run(n) {
let state = initial;
yield state;
for (let i = 0; i < n; i++) yield (state = next(i, state));
}
Insert cell
states = [...run(10)]
Insert cell
Insert cell
Insert cell
area = {
const final = states[10];
const [x1, x2] = d3.extent(final, (d) => d[0]);
const [y1, y2] = d3.extent(final, (d) => d[1]);
return (x2 - x1 + 1) * (y2 - y1 + 1);
}
Insert cell
part1 = area - states[10].size
Insert cell
function* run2() {
let state = initial;
let i = 0;
while (i < 1000) {
const n = next(i, state);
const moved = d3.filter(n, (p) => !state.has(p)).length;
if (moved === 0) break;
state = n;
i++;
if (i % 10 === 0) yield [i + 1, moved];
}
yield i + 1;
}
Insert cell
part2 = run2()
Insert cell
Insert cell
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