Public
Edited
Dec 4, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
testRucksacks = parseRucksacks(test)
Insert cell
testIntersections = testRucksacks.map(intersectCompartments)
Insert cell
function parseRucksack(rucksack) {
return [
rucksack.slice(0, rucksack.length / 2),
rucksack.slice(rucksack.length / 2)
];
}
Insert cell
function intersectCompartments(compartments) {
return d3.intersection(...compartments);
}
Insert cell
function prioritizeItem(item) {
if ("a" <= item && item <= "z") return item.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
if ("A" <= item && item <= "Z") return item.charCodeAt(0) - 'A'.charCodeAt(0) + 27;
throw new Error(`invalid item: ${item}`);
}
Insert cell
prioritizeItem("A")
Insert cell
input = FileAttachment("input.txt").text()
Insert cell
function parseRucksacks(input) {
return input.trim().split("\n").map(parseRucksack);
}
Insert cell
rucksacks = parseRucksacks(input)
Insert cell
intersections = rucksacks.map(intersectCompartments)
Insert cell
intersections.every((intersection) => intersection.size === 1)
Insert cell
priorities = intersections.map(([item]) => prioritizeItem(item))
Insert cell
d3.sum(priorities)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
testGroup1 = parseRucksacks(test1)
Insert cell
testGroup2 = parseRucksacks(test2)
Insert cell
intersectGroup(testGroup1)
Insert cell
intersectGroup(testGroup2)
Insert cell
function intersectGroup(rucksacks) {
return d3.intersection(...rucksacks.map((compartments) => compartments.join("")));
}
Insert cell
groups = d3.groups(rucksacks, (_, i) => Math.floor(i / 3)).map(([id, rucksacks]) => rucksacks)
Insert cell
groupIntersections = groups.map(intersectGroup)
Insert cell
groupIntersections.every((intersection) => intersection.size === 1)
Insert cell
d3.sum(groupIntersections, ([item]) => prioritizeItem(item))
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