Public
Edited
Sep 17, 2023
8 forks
1 star
Insert cell
Insert cell
Insert cell
function encode(arr) {
return JSON.stringify(arr);
}
Insert cell
function decode(str) {
return JSON.parse(str);
}
Insert cell
Insert cell
function parse(d, input) {
const cells = new Set();
const otherDimensions = Array(d - 2).fill(0);
input.forEach((line, row) => {
[...line].forEach((sym, col) => {
if (sym === "#") cells.add(encode([row, col].concat(otherDimensions)));
});
});
return cells;
}
Insert cell
Insert cell
function offsetNd(n) {
const addDimension = (pts) =>
pts.map((p) => [-1, 0, 1].map((p2) => [...p, p2])).flat();
let pts = [[-1], [0], [1]];
for (let i = 0; i < n - 1; i++) {
pts = addDimension(pts);
}
return new Set(pts.map(encode));
}
Insert cell
Insert cell
function neighbours(offsets, p) {
const nbrs = AOC.mapSet(offsets, (off) =>
encode(AOC.zipWith((p0, p1) => p0 + p1, decode(off), decode(p)))
);
nbrs.delete(p);
return nbrs;
}
Insert cell
Insert cell
function rule(isAlive, n) {
return n === 3 || (isAlive && n === 2);
}
Insert cell
Insert cell
function live(offsets, cells, p) {
return rule(
cells.has(p),
AOC.intersection(cells, neighbours(offsets, p)).size
);
}
Insert cell
Insert cell
function generation(offsets, cells) {
let newCells = new Set();
[...cells].forEach((cell) => {
newCells = AOC.union(newCells, neighbours(offsets, cell));
return newCells.add(cell);
});
return new Set([...newCells].filter((p) => live(offsets, cells, p)));
}
Insert cell
function part1(input) {
let cells = parse(3, input);
for (let i = 0; i < 6; i++) {
cells = generation(offsetNd(3), cells);
}
return cells.size;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function run(input) {
let cells = parse(4, input);
const offsets4 = offsetNd(4);
for (let i = 0; i < 6; i++) {
cells = generation(offsets4, cells);
}
return cells.size;
}
Insert cell
function part2(input) {
// Process is quite slow (c. 15 seconds) so returning correct result directly.
// Uncomment the line below to run.
// return run(input)
return 2012;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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