Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const fs = Graph();
let currentDir = "";
let parentDir = "";

input.split("\n").forEach((line) => {
if (line.startsWith("$ cd ")) {
let dir = line.slice(5);
if (dir === "..") {
currentDir = parentDir;
parentDir = fs.inNodes(parentDir)[0];
} else {
parentDir = currentDir;
currentDir = currentDir + "/" + dir;
}
} else if (!line.startsWith("$")) {
// We have directory contents being listed
if (line.startsWith("dir ")) {
fs.addEdge(currentDir, currentDir + "/" + line.slice(4).trim());
} else {
const tokens = line.split(" ");
fs.addEdge(currentDir, tokens[1] + "," + tokens[0]);
}
}
});
return fs;
}
Insert cell
Insert cell
function dirSizes(fs) {
const sizes = new Map();
fs.depthFirstSearch().forEach((file) => {
const tokens = file.split(",");
if (tokens.length === 2) {
// We have a file
AOC.addToFreqTable(sizes, fs.inNodes(file)[0], Number(tokens[1]));
} else {
// A dirctory, so add size of files sitting in it.
fs.adjacent(file)
.filter((d) => !d.includes(","))
.forEach((d) => AOC.addToFreqTable(sizes, file, sizes.get(d)));
}
});
return sizes;
}
Insert cell
Insert cell
function part1(input) {
return AOC.sum(
[...dirSizes(parse(input)).values()].filter((s) => s <= 100000)
);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const fs = parse(puzzleInput);
const sortedDirs = AOC.sort([...dirSizes(fs).values()], true);
const used = sortedDirs[0];
return AOC.takeWhile((x) => used - x < 40000000, sortedDirs).reverse()[0];
}
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