Public
Edited
Dec 9
Paused
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("").map(Number);
}
Insert cell
Insert cell
function defragBlocks(xs) {
const expand = (n, i) => Array(n).fill(i); // Converts a run-length tuple into actual values
const rles = xs.filter((_, i) => !(i % 2)).map((rle, i) => [rle, i]);
const gaps = xs.filter((_, i) => i % 2).reverse(); // Reverse so we can pop off the end
const [out, buffer] = [[], []];

rles.forEach((rle) => {
out.push(expand(...rle));
const gap = gaps.pop();
while (buffer.length < gap) {
buffer.push(...expand(...rles.pop()));
}
out.push(buffer.slice(0, gap));
buffer.splice(0, gap);
});
out.push(buffer); // Empty the buffer if any file blocks left

return d3.sum(out.flat(), (n, i) => n * i);
}
Insert cell
function part1(input) {
return defragBlocks(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function defragFiles(xs) {
const expand = (n, i) => Array(n).fill(i);
const rles = xs.filter((_, i) => !(i % 2)).map((rle, i) => [rle, i]);
const gaps = xs.filter((_, i) => i % 2).map((gap) => [gap, []]);

for (let i = rles.length - 1; i > 0; i--) {
for (let j = 0; j < i; j++) {
if (rles[i][0] <= gaps[j][0]) {
// We can move the file into a gap
gaps[j][0] -= rles[i][0]; // Shrink the gap
gaps[j][1].push(expand(...rles[i]));
rles[i][1] = 0; // Set the original file block IDs to 0 so ignored by checksum
break;
}
}
}

// Interleave files and gaps
const out = [];
for (let j = 0; j < gaps.length; j++) {
out.push(expand(...rles[j]));
out.push(...gaps[j][1]);
out.push(expand(gaps[j][0], 0));
}

return d3.sum(out.flat(), (n, i) => n * i);
}
Insert cell
function part2(input) {
return defragFiles(parse(input));
}
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