Public
Edited
Dec 2
Paused
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
const line = (txt, n) => txt.split("\n")[n];
const parseTest = (op, arg) => {
if (arg === "old") {
return (wl) => wl * wl;
}
if (op === "*") {
return (wl) => wl * Number(arg);
}
return (wl) => wl + Number(arg);
};
const parseMonkey = (txt) => ({
items: JSON.parse("[" + line(txt, 1).slice(18) + "]"),
operation: parseTest(line(txt, 2)[23], line(txt, 2).slice(25)),
divisor: Number(line(txt, 3).slice(21)),
tMonkey: Number(line(txt, 4).slice(29)),
fMonkey: Number(line(txt, 5).slice(30)),
inspected: 0
});

return input.split("\n\n").map(parseMonkey);
}
Insert cell
Insert cell
function play(monkeys, i) {
const monkey = monkeys[i];
monkey.inspected += monkey.items.length;
const test = (wl) =>
wl % monkey.divisor === 0 ? monkey.tMonkey : monkey.fMonkey;
while (monkey.items.length > 0) {
const wl = Math.floor(monkey.operation(monkey.items.shift()) / 3);
monkeys[test(wl)].items.push(wl);
}
return monkey;
}
Insert cell
Insert cell
function monkeyBusiness(monkeys) {
return AOC.product(
AOC.sort(
monkeys.map((m) => m.inspected),
true
).slice(0, 2)
);
}
Insert cell
function part1(input) {
const monkeys = parse(input);
for (let i = 0; i < 20; i++) {
monkeys.forEach((_, i) => play(monkeys, i));
}
return monkeyBusiness(monkeys);
}
Insert cell
Insert cell
Insert cell
Insert cell
function productOfDivisors(monkeys) {
return AOC.product(monkeys.map((m) => m.divisor));
}
Insert cell
Insert cell
function play2(monkeys, pod, i) {
const monkey = monkeys[i];
monkey.inspected += monkey.items.length;
const test = (wl) =>
wl % monkey.divisor === 0 ? monkey.tMonkey : monkey.fMonkey;
while (monkey.items.length > 0) {
const wl = monkey.operation(monkey.items.shift()) % pod;
monkeys[test(wl)].items.push(wl);
}
return monkey;
}
Insert cell
function part2(input) {
const monkeys = parse(input);
const pod = productOfDivisors(monkeys);
for (let i = 0; i < 10000; i++) {
monkeys.forEach((_, i) => play2(monkeys, pod, i));
}
return monkeyBusiness(monkeys);
}
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