Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
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
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 { label, op, val } = parse(token);
const box = hash(label);
if (op === "=") {
boxes[box][label] = val;
} else {
delete boxes[box][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

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