71 lines
1.6 KiB
JavaScript
71 lines
1.6 KiB
JavaScript
const fs = require('fs/promises');
|
|
|
|
const main = async () => {
|
|
const input = (await fs.readFile("./input.txt", 'utf8')).split("\n\n");
|
|
|
|
const getItem = (itemStr) => {
|
|
|
|
const val = parseFloat(itemStr);
|
|
|
|
const remainders = Array.from(Array(19).keys()).map((_, i) => val % (i + 1));
|
|
|
|
const isDivisibleBy = (n) => remainders[n - 1] === 0;
|
|
|
|
const inspect = str => {
|
|
remainders.forEach((rem, i) => {
|
|
const div = i + 1;
|
|
remainders[i] = eval(`const old = ${rem}; const _${str}; _new;`) % div;
|
|
});
|
|
};
|
|
|
|
return {
|
|
isDivisibleBy,
|
|
inspect
|
|
};
|
|
};
|
|
|
|
const getMonkey = (str) => {
|
|
const rows = str.split("\n").slice(1).map(r => r.split(": ")[1]);
|
|
|
|
const items = rows[0].split(", ").map(getItem);
|
|
|
|
const inspectOp = rows[1];
|
|
|
|
const testDiv = parseFloat(rows[2].split(" ")[2]);
|
|
|
|
const trueTarget = rows[3][rows[3].length - 1];
|
|
const falseTarget = rows[4][rows[4].length - 1];
|
|
|
|
let inspectCount = 0;
|
|
|
|
const takeTurn = () => {
|
|
while(items.length) {
|
|
inspectCount++;
|
|
const item = items.shift();
|
|
item.inspect(inspectOp);
|
|
|
|
|
|
monkeyData[item.isDivisibleBy(testDiv) ? trueTarget : falseTarget].addItem(item);
|
|
}
|
|
}
|
|
|
|
const addItem = (item) => items.push(item);
|
|
|
|
return {
|
|
takeTurn,
|
|
addItem,
|
|
getCount: () => inspectCount
|
|
};
|
|
};
|
|
|
|
const monkeyData = input.map(getMonkey);
|
|
|
|
for (let i = 0; i < 10000; ++i) {
|
|
monkeyData.forEach(m => m.takeTurn());
|
|
}
|
|
|
|
const counts = monkeyData.map(m => m.getCount()).sort((a, b) => b - a);
|
|
console.log(counts[0] * counts[1]);
|
|
}
|
|
|
|
main();
|