Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n\n").map((pair) => pair.split("\n").map(JSON.parse));
}
Insert cell
Insert cell
function comparator(l, r) {
if (!Array.isArray(l)) {
if (!Array.isArray(r)) {
return Math.sign(l - r); // Number vs number
}
return comparator([l], r); // Number vs array
}
if (!Array.isArray(r)) {
return comparator(l, [r]); // Array vs number
}
if (l.length === 0 && r.length === 0) {
return 0; // Two empty arrays
}
if (l.length === 0) {
return -1; // Left side empty before right
}
if (r.length === 0) {
return 1; // Right side empty before left.
}
// Compare each array element until one is greater than the other
for (let i = 0; i < Math.min(l.length, r.length); i++) {
const result = comparator(l[i], r[i]);
if (result !== 0) {
return result;
}
}
// Unequal array lengths
return Math.sign(l.length - r.length);
}
Insert cell
Insert cell
function part1(input) {
return AOC.sum(
parse(input).map((pair, i) => (comparator(...pair) === -1 ? i + 1 : 0))
);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const sorted = parse(input)
.flat()
.concat([[[2]], [[6]]])
.sort(comparator);

let i0, i1;
for (let i = 0; i < sorted.length; i++) {
if (AOC.equalArrays(sorted[i], [[2]])) {
i0 = i + 1;
} else if (AOC.equalArrays(sorted[i], [[6]])) {
i1 = i + 1;
}
}
return i0 * i1;
}
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