Public
Edited
Dec 1, 2023
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").reduce((acc, line) => {
const [depth, range] = line.split(": ").map(Number);
acc[depth] = range;
return acc;
}, {});
}

Insert cell
Insert cell
function calculateSeverity(firewall) {
return Object.keys(firewall).reduce((acc, depth) => {
const range = firewall[depth];
const cycleTime = (range - 1) * 2;
if (depth % cycleTime === 0) {
return acc + depth * range;
}
return acc;
}, 0);
}
Insert cell
function part1(input) {
return calculateSeverity(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function findDelay(firewall) {
let delay = 0;
const maxDepth = Math.max(...Object.keys(firewall).map(Number));

const nextCatch = Array(maxDepth + 1).fill(null);
for (const [depth, range] of Object.entries(firewall)) {
nextCatch[Number(depth)] = (range - 1) * 2;
}

while (true) {
let caught = false;
for (const [depth, period] of nextCatch.entries()) {
if (period !== null && (depth + delay) % period === 0) {
caught = true;
break;
}
}
if (!caught) {
return delay;
}
delay++;
}
}
Insert cell
function part2(input) {
return findDelay(parse(input));
}
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