Public
Edited
Dec 7, 2024
Paused
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const [order, page] = input.split("\n\n");

const orders = order.split("\n").reduce((map, d) => {
const [p1, p2] = d.split("|").map(Number);
map.set(p1, [...(map.get(p1) || []), p2]);
return map;
}, new Map());

const pages = page.split("\n").map((d) => d.split(",").map(Number));

return [orders, pages];
}
Insert cell
Insert cell
function sort(update, orders) {
return [...update].sort((a, b) => (orders.get(b)?.includes(a) ? 1 : -1));
}
Insert cell
Insert cell
function isValid(update, orders) {
return AOC.equalArrays(update, sort(update, orders));
}
Insert cell
Insert cell
function midSum(updates) {
return d3.sum(updates.map((d) => d[Math.floor(d.length / 2)]));
}
Insert cell
function part1(input) {
const [orders, updates] = parse(input);
return midSum(updates.filter((d) => isValid(d, orders)));
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
const [orders, updates] = parse(input);
const invalid = updates.filter((d) => !isValid(d, orders));
return midSum(invalid.map((d) => sort(d, orders)));
}
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