Public
Edited
Dec 15, 2023
Insert cell
Insert cell
Insert cell
function hash(str) {
return Array.from(str).reduce(
(h, c) => ((h + c.charCodeAt(0)) * 17) % 256,
0
);
}
Insert cell
function part1(input) {
return AOC.sum(input.split(",").map(hash));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(instr) {
const [, label, , val] = instr.match(/^([a-z]+)(=([0-9]+)|-)$/);
return {
label,
op: val ? "=" : "-",
...(val && { val: Number(val) })
};
}
Insert cell
Insert cell
function assignLenses(input) {
const boxes = new Array(256).fill().map(() => ({}));

for (const token of input) {
const instr = parse(token);
const box = hash(instr.label);
if (instr.op === "=") {
boxes[box][instr.label] = instr.val;
} else {
delete boxes[box][instr.label];
}
}
return boxes;
}
Insert cell
Insert cell
function power(boxes) {
return boxes.reduce(
(pwr, box, i) =>
pwr +
Object.values(box).reduce(
(sum, lens, j) => sum + (i + 1) * (j + 1) * lens,
0
),
0
);
}
Insert cell
function part2(input) {
return power(assignLenses(input.split(",")));
}
Insert cell
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