2022-12-11 18:30:44 +00:00
|
|
|
import * as R from "remeda";
|
|
|
|
|
|
|
|
import { readFile } from "../05/part1.js";
|
|
|
|
|
|
|
|
function parseMonkey(block) {
|
|
|
|
const re = new RegExp(
|
|
|
|
`Starting items: (?<items>.+)
|
|
|
|
Operation: new = (?<operation>.+)
|
|
|
|
Test: divisible by (?<divisible>\\d+)
|
|
|
|
If true: throw to monkey (?<ifTrue>\\d+)
|
|
|
|
If false: throw to monkey (?<ifFalse>\\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) => {
|
2022-12-12 00:32:35 +00:00
|
|
|
monkey.inspections += monkey.items.length;
|
2022-12-11 18:30:44 +00:00
|
|
|
|
2022-12-12 00:32:35 +00:00
|
|
|
monkey.items = monkey.items.map((i) => monkey.operation(i));
|
2022-12-11 18:30:44 +00:00
|
|
|
|
2022-12-12 00:32:35 +00:00
|
|
|
monkey.items = monkey.items.map((i) => Math.floor(i / 3));
|
2022-12-11 18:30:44 +00:00
|
|
|
|
2022-12-12 00:32:35 +00:00
|
|
|
monkey.items.forEach((i) => {
|
|
|
|
monkeys[i % monkey.divisible ? monkey.ifFalse : monkey.ifTrue].items.push(
|
|
|
|
i
|
|
|
|
);
|
|
|
|
});
|
2022-12-11 18:30:44 +00:00
|
|
|
|
2022-12-12 00:32:35 +00:00
|
|
|
monkey.items = [];
|
2022-12-11 18:30:44 +00:00
|
|
|
|
2022-12-12 00:32:35 +00:00
|
|
|
return;
|
2022-12-11 18:30:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
const playRound = (monkeys) => {
|
2022-12-12 00:32:35 +00:00
|
|
|
monkeys.forEach((monkey) => playTurn(monkeys, monkey));
|
|
|
|
return monkeys;
|
|
|
|
};
|
2022-12-11 18:30:44 +00:00
|
|
|
|
|
|
|
export default R.createPipe(
|
2022-12-12 00:32:35 +00:00
|
|
|
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)
|
|
|
|
);
|