Public
Edited
Dec 11, 2021
1 star
Insert cell
Insert cell
Insert cell
function createDEM(input) {
const cells = input.split("\n").map((s) => s.split("").map(Number));
const dem = [];
const nCols = cells[0].length + 2;
dem.push(new Array(nCols).fill(10));
cells.forEach((row) => dem.push([10, ...row.map(AOC.identity), 10]));
dem.push(new Array(nCols).fill(10));
return dem;
}
Insert cell
Insert cell
Insert cell
function findPits(dem) {
const pits = [];
for (let row = 1; row < dem.length - 1; row++) {
for (let col = 1; col < dem[0].length - 1; col++) {
const z = dem[row][col];

if (
z < dem[row - 1][col] &&
z < dem[row + 1][col] &&
z < dem[row][col - 1] &&
z < dem[row][col + 1]
) {
pits.push([row, col, z]);
}
}
}
return pits;
}
Insert cell
Insert cell
function part1(input) {
return AOC.sum(findPits(createDEM(input)).map(([r, c, z]) => z + 1));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function fill(dem, r, c, basin) {
if (dem[r][c] < 9) {
dem[r][c] = "B" + basin;
fill(dem, r - 1, c, basin);
fill(dem, r + 1, c, basin);
fill(dem, r, c - 1, basin);
fill(dem, r, c + 1, basin);
}
}
Insert cell
Insert cell
function part2(input) {
const dem = createDEM(input);
const pits = findPits(dem);
const basins = [];
pits.forEach(([r, c, z], i) => {
fill(dem, r, c, i);
basins.push(dem.flat().filter((z) => z == "B" + i).length);
});
return AOC.product(AOC.sort(basins, true).slice(0, 3));
}
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