Public
Edited
Sep 17, 2023
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
const lines = input
.map((s) =>
s.match(/(.+) x=(-?\d+)..(-?\d+),y=(-?\d+)..(-?\d+),z=(-?\d+)..(-?\d+)/)
)
.map((l) => [l[1] == "on" ? 1 : -1, ...l.slice(2, 8).map(Number)]);

const oNames = ["lit", "xMin", "xMax", "yMin", "yMax", "zMin", "zMax"];
return lines.map((l) =>
Object.fromEntries(AOC.zipWith((k, v) => [k, Number(v)], oNames, l))
);
}
Insert cell
Insert cell
Insert cell
function intersections(c, cubes) {
const ics = [];

const intersect = (c1, c2) =>
c1.xMax < c2.xMin ||
c1.xMin > c2.xMax ||
c1.yMax < c2.yMin ||
c1.yMin > c2.yMax ||
c1.zMax < c2.zMin ||
c1.zMin > c2.zMax
? null
: {
lit: c2.lit,
xMin: Math.max(c1.xMin, c2.xMin),
xMax: Math.min(c1.xMax, c2.xMax),
yMin: Math.max(c1.yMin, c2.yMin),
yMax: Math.min(c1.yMax, c2.yMax),
zMin: Math.max(c1.zMin, c2.zMin),
zMax: Math.min(c1.zMax, c2.zMax)
};

for (const cube of cubes) {
const ic = intersect(c, cube);
if (ic) {
ics.push(ic);
}
}
return ics;
}
Insert cell
function volume(cube) {
if (cube) {
const w = cube.xMax - cube.xMin + 1;
const h = cube.yMax - cube.yMin + 1;
const d = cube.zMax - cube.zMin + 1;
return cube.lit * (w * h * d);
}
return 0;
}
Insert cell
Insert cell
function reboot(cubes) {
const processed = [];
for (const cube of cubes) {
processed.push(
...intersections(cube, processed).map((c) => {
c.lit = -1 * c.lit;
return c;
})
);

if (cube.lit == 1) {
processed.push(cube);
}
}
return processed.reduce((vol, cube) => vol + volume(cube), 0);
}
Insert cell
Insert cell
function part1(input) {
const cubes = parse(puzzleInput).filter(
(c) =>
c.xMin >= -50 &&
c.xMax <= 50 &&
c.yMin >= -50 &&
c.yMax <= 50 &&
c.zMin >= -50 &&
c.zMax <= 50
);
return reboot(cubes);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return reboot(parse(puzzleInput));
}
Insert cell
Insert cell
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