Public
Edited
Dec 11, 2021
2 stars
Insert cell
Insert cell
Insert cell
function addBorder(input) {
const cells = input.split("\n").map((s) => s.split("").map(Number));
const nCols = cells[0].length + 2;
const grid = [];

grid.push(new Array(nCols).fill(0));
cells.forEach((row) => grid.push([0, ...row.map(AOC.identity), 0]));
grid.push(new Array(nCols).fill(0));
return grid;
}
Insert cell
Insert cell
Insert cell
function increment(row, col, grid) {
if (row == 0 || col == 0 || row == 11 || col == 11) {
return; // Stop when we've hit the edge.
}
grid[row][col]++;
if (grid[row][col] == 10) {
increment(row - 1, col - 1, grid);
increment(row - 1, col, grid);
increment(row - 1, col + 1, grid);
increment(row, col - 1, grid);
increment(row, col + 1, grid);
increment(row + 1, col - 1, grid);
increment(row + 1, col, grid);
increment(row + 1, col + 1, grid);
}
}
Insert cell
Insert cell
function tick(grid) {
for (let row = 1; row <= 10; row++) {
for (let col = 1; col <= 10; col++) {
increment(row, col, grid);
}
}
// Count flashes
let flashes = 0;
for (let row = 1; row <= 10; row++) {
for (let col = 1; col <= 10; col++) {
if (grid[row][col] > 9) {
grid[row][col] = 0;
flashes++;
}
}
}
return flashes;
}
Insert cell
function part1(input) {
const grid = addBorder(input);
let flashes = 0;
for (let n = 0; n < 100; n++) {
flashes += tick(grid);
}
return flashes;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const grid = addBorder(input);
let n = 1;
while (tick(grid) != 100) {
n++;
}
return n;
}
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