Public
Edited
Dec 30, 2022
1 fork
Importers
1 star
Insert cell
Insert cell
Insert cell
parse = aoc.paragraphs((p, id) => {
let lines = p.split("\n").map((l) => l.split(": "));
lines.shift(); // monkey index
let startingItems = Array.from(
lines.shift()[1].matchAll(/\d+/g),
(match) => +match[0]
);
let [, , argA, op, argB] = lines.shift()[1].split(" ").map(maybeNum);
return {
id,
items: startingItems,
op: { argA, argB, op },
divisor: +lines.shift()[1].match(/\d+/)[0],
ifTrue: +lines.shift()[1].match(/\d+/)[0],
ifFalse: +lines.shift()[1].match(/\d+/)[0]
};
})
Insert cell
monkeyBusiness = ({ monkeys, rounds, relief }) => {
monkeys = _.cloneDeep(monkeys);
let modulo = monkeys.map((m) => m.divisor).reduce(aoc.lcm);
let inspectionCount = monkeys.map(() => 0);
for (let round = 0; round < rounds; round++) {
for (const monkey of monkeys) {
let items = monkey.items;
monkey.items = [];
for (let item of items) {
// inspect
inspectionCount[monkey.id] += 1;
let { op, argA, argB } = monkey.op;
if (argA === "old") argA = item;
if (argB === "old") argB = item;
item = (op === "*" ? argA * argB : argA + argB) % modulo;
// relief
if (relief) item = Math.floor(item / 3);
// throw
let throwTarget =
item % monkey.divisor === 0 ? monkey.ifTrue : monkey.ifFalse;
monkeys[throwTarget].items.push(item);
}
}
}
inspectionCount = d3.sort(inspectionCount);
return inspectionCount.at(-1) * inspectionCount.at(-2);
}
Insert cell
part1 = (monkeys) => monkeyBusiness({ monkeys, rounds: 20, relief: true })
Insert cell
part2 = (monkeys) => monkeyBusiness({ monkeys, rounds: 10_000, relief: false })
Insert cell
parse(inputs.real)
.map((m) => m.divisor)
.reduce(aoc.lcm)
Insert cell
Insert cell
function maybeNum(s) {
let n = +s;
if (isNaN(n)) return s;
return n;
}
Insert cell
Insert cell
meta = aoc.meta({
day: 11,
parse,
inputs,
parts: [part1, part2],
expected: { test: [10605, 2713310158], real: [107822, 27267163742] },
href: "https://observablehq.com/d/4c693833157b1215?collection=@mythmon/advent-of-code-2022"
})
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