adventofcode/2022/11/part1.js
2022-12-11 19:38:10 -05:00

72 lines
1.6 KiB
JavaScript

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) => {
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)
);