const fs = require('fs'); const readline = require('readline'); const SCREEN_WIDTH = 40; //const RELIEF = BigInt(3); // part 1 const RELIEF = BigInt(1); // part 2 function Monkey(monkeyPool, id) { this.pool = monkeyPool; this.id = id; this.items = []; this.operation = i => i; this.testValue = 0; this.ifTrue = null; this.ifFalse = null; this.inspect = 0; } Monkey.prototype.setOperation = function(line) { this.operator = line.substring(0, 1); let other = line.substring(2); this.operation = i => { let _other = other === 'old' ? i : BigInt(parseInt(other)); switch (this.operator) { case '+': i = i + _other; break; case '*': i = i * _other; break; } return RELIEF == 1 ? (i % this.pool.maxDiv): Math.floor(Number(i / RELIEF)); }; } Monkey.prototype.run = function() { this.inspect += this.items.length; while (this.items.length) { let i = this.items.shift(); i = this.operation(i); this.pool.monkeys[(i % this.testValue == 0) ? this.ifTrue : this.ifFalse].items.push(i); } } function MonkeyPool() { this.monkeys = []; this.maxDiv = 0; } MonkeyPool.prototype.push = function(i) { let m = new Monkey(this, i); this.monkeys[i] = m; return i; } MonkeyPool.prototype.round = function() { for (let i of this.monkeys) i.run(); } MonkeyPool.prototype.debug = function() { for (let i of this.monkeys) console.log(i.id, i.inspect, i.items); } async function main() { let monkeys = new MonkeyPool(); let currentMonkey = null; for await (let line of readline.createInterface({ input: process.stdin })) { line = line.trim(); if (!line || !line.length) currentMonkey = null; else if (line.startsWith('Monkey ')) currentMonkey = monkeys.push(parseInt(line.substr(7))); else if (line.startsWith('Starting items: ')) monkeys.monkeys[currentMonkey].items = line.substring('Starting items: '.length).split(',').map(i => BigInt(parseInt(i.trim()))); else if (line.startsWith('Operation: new = old ')) monkeys.monkeys[currentMonkey].setOperation(line.substring('Operation: new = old '.length)); else if (line.startsWith('Test: divisible by ')) monkeys.monkeys[currentMonkey].testValue = BigInt(parseInt(line.substring('Test: divisible by'.length))); else if (line.startsWith('If true: throw to monkey ')) monkeys.monkeys[currentMonkey].ifTrue = parseInt(line.substring('If true: throw to monkey '.length)); else if (line.startsWith('If false: throw to monkey ')) monkeys.monkeys[currentMonkey].ifFalse = parseInt(line.substring('If false: throw to monkey '.length)); } monkeys.maxDiv = monkeys.monkeys.map(i => i.testValue).reduce((a, b) => a ? (a * b) : b); for (let i =0; i < 10000; ++i) monkeys.round(); console.log(monkeys.monkeys.map(i => i.inspect).sort((a, b) => b -a).slice(0, 2).reduce((a, b) => a ? a*b : b)); console.log(monkeys.monkeys.map(i => i.inspect)); }; (main());