Public
Edited
Dec 20, 2021
3 stars
Insert cell
Insert cell
Insert cell
function parse(input) {
let [alg, grd] = input.split("\n\n");
alg = alg.replaceAll(".", 0).replaceAll("#", 1);

grd = grd
.split("\n")
.map((l) => l.replaceAll(".", 0).replaceAll("#", 1).split(""));
return [alg, grd];
}
Insert cell
Insert cell
Insert cell
Insert cell
function enhancePixel(row, col, grd, alg, isEven) {
const dflt = isEven ? "0" : alg[0];
const cellAt = (r, c) =>
r < 0 || c < 0 || r >= grd.length || c >= grd[0].length ? dflt : grd[r][c];

const window =
cellAt(row - 1, col - 1) +
cellAt(row - 1, col) +
cellAt(row - 1, col + 1) +
cellAt(row, col - 1) +
cellAt(row, col) +
cellAt(row, col + 1) +
cellAt(row + 1, col - 1) +
cellAt(row + 1, col) +
cellAt(row + 1, col + 1);

return alg[parseInt(window, 2)];
}
Insert cell
Insert cell
function expand(grd, alg, isEven) {
const o = isEven ? "0" : alg[0];

// Add new top and bottom rows
grd.reverse().push(new Array(grd.length).fill(o));
grd.reverse();
grd.push(new Array(grd[0].length).fill(o));

// Add new left and right columns
grd.map((row) => {
row.reverse().push(o);
row.reverse();
row.push(o);
});

return grd;
}
Insert cell
Insert cell
function enhance(grd, alg, isEven) {
expand(grd, alg, isEven);
const newGrid = AOC.cloneArray(grd);
for (let row = 0; row < newGrid.length; row++) {
for (let col = 0; col < newGrid[0].length; col++) {
newGrid[row][col] = enhancePixel(row, col, grd, alg, isEven);
}
}
return newGrid;
}
Insert cell
Insert cell
function part1(input) {
let [alg, grd] = parse(puzzleInput);

grd = enhance(grd, alg, true);
grd = enhance(grd, alg, false);

return grd.flat().filter((c) => c == "1").length;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
let [alg, grd] = parse(puzzleInput);

for (let i = 0; i < 50; i++) {
grd = enhance(grd, alg, i % 2 == 0);
}
return grd.flat().filter((c) => c == "1").length;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function display(grid) {
const nRows = grid.length;
const nCols = grid[0].length;
const r = new Renderer(600, 600)
.fit([
[-1, -1],
[nRows, nCols]
])
.stroke();
grid
.flat()
.forEach((b, i) =>
b === "1" ? r.ellipse(i % nCols, Math.floor(i / nCols), 0.5) : r
);
return r.render();
}
Insert cell
display(parse(puzzleInput)[1])
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