Public
Edited
Dec 13, 2022
1 fork
1 star
Insert cell
Insert cell
test = `[1,1,3,1,1]
[1,1,5,1,1]

[[1],[2,3,4]]
[[1],4]

[9]
[[8,7,6]]

[[4,4],4,4]
[[4,4],4,4,4]

[7,7,7,7]
[7,7,7]

[]
[3]

[[[]]]
[[]]

[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
`
Insert cell
testPacketPairs = parsePacketPairs(test)
Insert cell
function parsePacketPairs(input) {
return input.trim().split("\n\n").map(parsePacketPair);
}
Insert cell
function parsePacketPair(input) {
return input.split("\n").map(JSON.parse);
}
Insert cell
comparePacketValue(...testPacketPairs[7])
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
comparePacketValue(1, [])
Insert cell
d3.sum(testPacketPairs, ([left, right], i) => comparePacketValue(left, right) < 0 ? i + 1 : 0)
Insert cell
input = FileAttachment("input.txt").text()
Insert cell
packetPairs = parsePacketPairs(input)
Insert cell
d3.sum(packetPairs, ([left, right], i) => comparePacketValue(left, right) < 0 ? i + 1 : 0)
Insert cell
decodePacketPairs(testPacketPairs)
Insert cell
decodePacketPairs(packetPairs)
Insert cell
function decodePacketPairs(packetPairs) {
const da = [[2]];
const db = [[6]];
const sortedPacketPairs = d3.sort(packetPairs.flat().concat([da, db]), comparePacketValue);
const ia = sortedPacketPairs.indexOf(da);
const ib = sortedPacketPairs.indexOf(db);
return (ia + 1) * (ib + 1);
}
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