Public
Edited
Dec 5
Insert cell
Insert cell
{
let [rulesStr, manualsStr] = txt.split("\n\n");

let ruleset = rulesStr
.split("\n")
.map((line) => line.split("|").map(Number))
.reduce((map, [k, v]) => {
if (!map.has(k)) map.set(k, new Set());
map.get(k).add(v);
return map;
}, new Map());

return manualsStr.split("\n").reduce(
(acc, line) => {
let manual = line.split(",").map(Number);
let sorted = manual.toSorted(
// custom compare function using the ruleset
(a, b) => (ruleset.get(a)?.has(b) ? -1 : 1)
);
let middlePage = sorted[Math.floor(sorted.length / 2)];
if (manual.every((p, i) => p === sorted[i])) {
acc.part1 += middlePage;
} else {
acc.part2 += middlePage;
}
return acc;
},
{ part1: 0, part2: 0 }
);
}
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