Public
Edited
Dec 11, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
import { chart } with { tosses as data } from "@d3/directed-chord-diagram"
Insert cell
tosses = result.flatMap((m, source) => m.targets.map((value, target) => ({source, target, value})))
Insert cell
part2 = business(result)
Insert cell
result = run(10000, (n) => n % product)
Insert cell
product = monkeys.reduce((n, m) => n * m.test, 1)
Insert cell
part1 = business(run(20))
Insert cell
business = (monkeys) => {
const [a, b] = monkeys.sort((a, b) => b.inspects - a.inspects);
return a.inspects * b.inspects;
}
Insert cell
function run(n, relief) {
let state = monkeys;
for (let i = 0; i < n; i++) state = round(state, relief);
return state;
}
Insert cell
function round(monkeys, relief) {
monkeys = monkeys.map(({ items, targets, ...rest }) => ({
items: items.slice(),
targets: targets.slice(),
...rest
}));

for (const monkey of monkeys) {
for (const { to, worry } of turn(monkey, relief)) {
monkeys[to].items.push(worry);
monkey.targets[to] = (monkey.targets[to] || 0) + 1;
}
monkey.inspects += monkey.items.length;
monkey.items = [];
}

return monkeys;
}
Insert cell
d3.map(turn(monkeys[0]), d => d)
Insert cell
function* turn({ items, inspect, test, throws }, relief = (w) => Math.floor(w / 3)) {
for (let worry of items) {
worry = inspect(worry);
worry = relief(worry);
yield { to: throws[worry % test === 0], worry };
}
}
Insert cell
monkeys = data
.trim()
.split("\n\n")
.map((p, i, all) => {
const starting = p.match(/Starting items: (.*)/)[1];
const items = starting.split(", ").map(Number);
const inspect = eval(`(old) => ${p.match(/Operation: new = (.*)/)[1]}`);
const test = +p.match(/Test: divisible by (\d+)/)[1];
const throws = {
true: +p.match(/If true: throw to monkey (\d+)/)[1],
false: +p.match(/If false: throw to monkey (\d+)/)[1]
};
return { items, inspect, test, throws, inspects: 0, targets: new Array(all.length).fill(0) };
})
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