94 lines
2.3 KiB
TypeScript
94 lines
2.3 KiB
TypeScript
import { readFileSync } from 'fs';
|
|
import { join } from 'path';
|
|
|
|
|
|
const fileString = readFileSync(join(__dirname, "input"), 'utf-8');
|
|
var rows = fileString.split("Monkey ");
|
|
|
|
rows = rows.map(val => {
|
|
return val.trim();
|
|
});
|
|
rows = rows.filter(val => {
|
|
return val.length > 0;
|
|
});
|
|
|
|
var mdata = rows.map(val => {
|
|
return val.split("\n").map(vval => {
|
|
return vval.trim();
|
|
}).filter(vval => {
|
|
return vval.length >0;
|
|
});
|
|
})
|
|
|
|
var monkeys = {}
|
|
|
|
for (const monkey of mdata) {
|
|
const monkeyName = +monkey[0].split(":")[0].trim();
|
|
const items = monkey[1].split(":")[1].trim().split(",").map(val => {
|
|
return BigInt(+val);
|
|
});
|
|
const op = monkey[2].split(":")[1].trim().split("=")[1].trim();
|
|
const divisTest = +monkey[3].split("by ")[1].trim();
|
|
const trueTarget = +monkey[4].split("monkey ")[1].trim();
|
|
const falseTarget = +monkey[5].split("monkey ")[1].trim();
|
|
monkeys[monkeyName] = {};
|
|
|
|
monkeys[monkeyName]['items'] = items;
|
|
monkeys[monkeyName]['operation'] = op;
|
|
monkeys[monkeyName]['test'] = BigInt(divisTest);
|
|
monkeys[monkeyName]['trueTarget'] = trueTarget;
|
|
monkeys[monkeyName]['falseTarget'] = falseTarget;
|
|
monkeys[monkeyName]['inspections'] = BigInt(0);
|
|
}
|
|
|
|
console.log(monkeys);
|
|
|
|
const ROUNDS = 10000;
|
|
|
|
var lcms = [];
|
|
for (const m in monkeys) {
|
|
lcms.push(monkeys[m]['test']);
|
|
}
|
|
|
|
const lcm = BigInt(lcms.reduce((a, b) => {
|
|
return a * b;
|
|
}));
|
|
|
|
for (var i = 0; i < ROUNDS; i++) {
|
|
for (const m in monkeys) {
|
|
const monkey = monkeys[m];
|
|
const ilen = monkey['items'].length;
|
|
for (var j = 0; j < ilen; j++) {
|
|
var item = BigInt(monkey['items'].shift());
|
|
|
|
var opstr = monkey['operation'].replace(/old/gi, item);
|
|
var opitms = opstr.split(" ");
|
|
opitms[0] = "BigInt(" + opitms[0] + ")";
|
|
opitms[2] = "BigInt(" + opitms[2] + ")";
|
|
opstr = opitms.join(" ");
|
|
|
|
item = BigInt(eval(opstr)) % lcm;
|
|
if ((item % monkey['test']) == BigInt(0)) {
|
|
monkeys[monkey['trueTarget']]['items'].push(item);
|
|
} else {
|
|
monkeys[monkey['falseTarget']]['items'].push(item);
|
|
}
|
|
monkey['inspections'] += BigInt(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log(monkeys);
|
|
|
|
var insCount = [];
|
|
for (const m in monkeys) {
|
|
insCount.push(monkeys[m]['inspections']);
|
|
}
|
|
console.log(insCount);
|
|
insCount = insCount.sort().slice(insCount.length - 2);
|
|
console.log(insCount);
|
|
|
|
console.log(insCount.reduce((a, b) => {
|
|
return a * b;
|
|
}));
|