Public
Edited
Dec 2
Paused
1 fork
4 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const rocks = input
.split("\n")
.map((l) => l.split(" -> ").map((pair) => pair.split(",").map(Number)));
const [minX, maxX, maxY] = [
Math.min(...rocks.flat().map(([x, y]) => x)),
Math.max(...rocks.flat().map(([x, y]) => x)),
Math.max(...rocks.flat().map(([x, y]) => y))
];
const startX = 500 - minX;
const cave = AOC.gInit(maxY + 1, maxX - minX + 1, ".");
const addSeg = ([x0, y0], [x1, y1]) => {
for (let x = Math.min(x0, x1); x <= Math.max(x0, x1); x++) {
for (let y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) {
cave[y][x - minX] = "#";
}
}
};

rocks.forEach((path) => {
for (let i = 1; i < path.length; i++) {
addSeg(path[i - 1], path[i]);
}
});
return [startX, cave];
}
Insert cell
Insert cell
function drop(r, c, cave) {
if (cave[r][c] === "o") {
return false; // Cave has filled back up to the source.
}
if (r >= cave.length - 1) {
return false; // Fallen off the bottom.
}
if (cave[r + 1][c] === ".") {
return drop(r + 1, c, cave); // Keep on falling
}
if (c === 0) {
return false; // Fallen off left edge
}
if (cave[r + 1][c - 1] === ".") {
return drop(r + 1, c - 1, cave); // Fall to left
}
if (c === cave[0].length - 1) {
return false; // Fallen off right edge.
}
if (cave[r + 1][c + 1] === ".") {
return drop(r + 1, c + 1, cave); // Fall to right
}
// Come to rest
cave[r][c] = "o";
return [c, r];
}
Insert cell
Insert cell
function countSand([startX, cave]) {
let i = 0;
while ((i, drop(0, startX, cave))) {
i++;
}
return i;
}
Insert cell
function part1(input) {
return countSand(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const depth = parse(input)[1].length; // Depth of cave before adding bottom layer
// Add a bottom layer to cave
return countSand(
parse(
input + `\n${499 - depth},${depth + 1} -> ${501 + depth},${depth + 1}`
)
);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
import { Renderer } from "@jwolondon/renderer"
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