Public
Edited
Dec 13, 2022
Paused
1 fork
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
grammar = `
List = LBracket inner:(
(((Number / List ) ","?)*)
) RBracket { return inner.map(d => d[0]) }

LBracket = "["
RBracket = "]"

Number = [0-9]+ { return +text() }
`
Insert cell
parser = pegjs.generate(grammar)
Insert cell
parse = aoc.paragraphLines((l) => parser.parse(l))
// this would work, but it feels wrong
// parse = aoc.paragraphLines((l) => eval(l))
Insert cell
function part1(input) {
return input
.map((d, i) => [d, i])
.filter(([[left, right]]) => inOrder(left, right))
.map(([d, i]) => i + 1)
.reduce((a, b) => a + b);
}
Insert cell
function part2(input) {
let marker1 = [[2]];
let marker2 = [[6]];
let ds = [...input.flat(), marker1, marker2];
ds.sort((a, b) => {
let x = inOrder(a, b);
if (x === null) return 0;
return x ? -1 : 1;
});
return (
(_.findIndex(ds, (d) => d === marker1) + 1) *
(_.findIndex(ds, (d) => d === marker2) + 1)
);
}
Insert cell
inOrder = {
return function inner(a, b) {
if (typeof a === "number" && typeof b === "number") {
if (a < b) return true;
if (a > b) return false;
return null;
}
if (typeof a === "number") a = [a];
if (typeof b === "number") b = [b];

for (const [left, right] of _.zip(a, b)) {
if (left === undefined) return true;
if (right === undefined) return false;
let x = inner(left, right);
if (x !== null) return x;
}

return null;
};
}
Insert cell
Insert cell
Insert cell
pegjs = import("https://cdn.skypack.dev/pegjs@0.10.0?min").then(
(mod) => mod.default
)
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