Public
Edited
Dec 15, 2022
Insert cell
Insert cell
Insert cell
input = FileAttachment("AoC_day13.txt").text()
Insert cell
function parsePacketPair(input) {
return input.split("\n").map(JSON.parse);
}
Insert cell
function parsePacketPairs(input) {
return input.trim().split("\n\n").map(parsePacketPair);
}
Insert cell
function comparePacketValue(left, right) {
if (typeof left === "number" && typeof right === "number") {
return d3.ascending(left, right);
}
if (Array.isArray(left) && Array.isArray(right)) {
const nl = left.length;
const nr = right.length;
let i = 0;
for (const n = Math.min(nl, nr); i < n; ++i) {
const c = comparePacketValue(left[i], right[i]);
if (c) return c;
}
return nl < nr ? -1 : nl > nr ? 1 : 0;
}
if (typeof left === "number" && Array.isArray(right)) {
return comparePacketValue([left], right);
}
if (Array.isArray(left) && typeof right === "number") {
return comparePacketValue(left, [right]);
}
throw new Error(`invalid comparison: ${left} vs. ${right}`);
}
Insert cell
packetPairs = parsePacketPairs(input)
Insert cell
d3.sum(packetPairs, ([left, right], i) => comparePacketValue(left, right) < 0 ? i + 1 : 0)
Insert cell
Insert cell
Insert cell
decodePacketPairs(packetPairs)
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