advent-of-code/2022/11/index.js

51 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-12-11 08:33:42 +00:00
const fs = require('fs/promises');
const sum = (arr) => arr.reduce((total, num) => total+num, 0);
const main = async () => {
const input = (await fs.readFile("./input.txt", 'utf8')).split("\n\n");
const getMonkey = (str) => {
const rows = str.split("\n").slice(1).map(r => r.split(": ")[1]);
const testItem = (item) => !(item % rows[2].split(" ")[2]);
const items = rows[0].split(", ").map(x => parseFloat(x));
const inspectItem = (old) => Math.floor(eval(`const old = ${old}; const item${rows[1]}; itemnew;`)/3);
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();
const inspectedItem = inspectItem(item);
monkeyData[testItem(inspectedItem) ? trueTarget : falseTarget].addItem(inspectedItem);
}
}
const addItem = (item) => items.push(item);
return {
takeTurn,
addItem,
getCount: () => inspectCount
};
};
const monkeyData = input.map(getMonkey);
for (let i = 0; i < 20; ++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();