import * as R from "remeda"; import { readFile } from "../05/part1.js"; function parseMonkey(block) { const re = new RegExp( `Starting items: (?.+) Operation: new = (?.+) Test: divisible by (?\\d+) If true: throw to monkey (?\\d+) If false: throw to monkey (?\\d+)`, "s" ); const groups = { ...block.match(re).groups }; ["divisible", "ifTrue", "ifFalse"].forEach( (k) => (groups[k] = parseInt(groups[k])) ); groups.operation = eval("(old) => " + groups.operation); groups.items = groups.items.split(", ").map((x) => parseInt(x)); return { ...groups, inspections: 0 }; } const readInput = (...args) => R.pipe( readFile(...args), (lines) => lines.split("\n\n"), R.compact, // remove last line R.map(parseMonkey) ); export const puzzleInput = readInput(import.meta.url, "input"); export const sample = readInput(import.meta.url, "sample"); const playTurn = (monkeys, monkey) => { monkey.inspections += monkey.items.length; monkey.items = monkey.items.map((i) => monkey.operation(i)); monkey.items = monkey.items.map((i) => Math.floor(i / 3)); monkey.items.forEach((i) => { monkeys[i % monkey.divisible ? monkey.ifFalse : monkey.ifTrue].items.push( i ); }); monkey.items = []; return; }; const playRound = (monkeys) => { monkeys.forEach((monkey) => playTurn(monkeys, monkey)); return monkeys; }; export default R.createPipe( R.clone, (monkeys) => R.times(20, () => playRound(monkeys)), R.last(), R.map(R.prop("inspections")), R.sortBy(R.identity), R.reverse, R.take(2), R.reduce((a, b) => a * b, 1) );