adventofcode2022/11/code.js

164 lines
2.9 KiB
JavaScript

const sampleMonkeys = [
[
[79, 98],
['*', 19],
[23, 2, 3],
0
],
[
[54, 65, 75, 74],
['+', 6],
[19, 2, 0],
0
],
[
[79, 60, 97],
['*', 'self'],
[13, 1, 3],
0
],
[
[74],
['+', 3],
[17, 0, 1],
0
],
]
const inputMonkeys = [
[
[91, 58, 52, 69, 95, 54],
['*', 13],
[7, 1, 5],
0
],
[
[80, 80, 97, 84],
['*', 'self'],
[3, 3, 5],
0
],
[
[86, 92, 71],
['+', 7],
[2, 0, 4],
0
],
[
[96, 90, 99, 76, 79, 85, 98, 61],
['+', 4],
[11, 7, 6],
0
],
[
[60, 83, 68, 64, 73],
['*', 19],
[17, 1, 0],
0
],
[
[96, 52, 52, 94, 76, 51, 57],
['+', 3],
[5, 7, 3],
0
],
[
[75],
['+', 5],
[13, 4, 2],
0
],
[
[83, 75],
['+', 1],
[19, 2, 6],
0
]
]
// Part One
//let monkeys = JSON.parse(JSON.stringify(sampleMonkeys));
let monkeys = JSON.parse(JSON.stringify(inputMonkeys));
for (let i = 0; i < 20; i++) {
for (const m in monkeys) {
const items = monkeys[m][0];
const op = monkeys[m][1];
const test = monkeys[m][2];
for (const item of items) {
monkeys[m][3]++;
let newLevel;
if (op[0] === '*') {
if (op[1] === 'self') {
newLevel = item * item;
} else {
newLevel = item * op[1];
}
} else {
newLevel = item + op[1];
}
newLevel = Math.floor(newLevel / 3);
if (newLevel % test[0] === 0) {
monkeys[test[1]][0].push(newLevel);
} else {
monkeys[test[2]][0].push(newLevel);
}
}
monkeys[m][0] = [];
}
}
let counts = monkeys.map(m => m[3]);
counts.sort(function(a, b) {
return b - a;
});
console.log(counts[0] * counts[1]);
// Part Two
//monkeys = JSON.parse(JSON.stringify(sampleMonkeys));
monkeys = JSON.parse(JSON.stringify(inputMonkeys));
// Common denominator trick to keep numbers small outright stolen from
// https://git.genehack.net/genehack/advent-of-code-2022/src/branch/main/11/day11_2.js
let COMMON = 1;
for (const monkey of monkeys) {
COMMON *= monkey[2][0];
}
for (let i = 0; i < 10000; i++) {
for (const m in monkeys) {
const items = monkeys[m][0];
const op = monkeys[m][1];
const test = monkeys[m][2];
for (const n in items) {
monkeys[m][3] = monkeys[m][3] + 1;
let newLevel;
if (op[0] === '*') {
if (op[1] === 'self') {
newLevel = monkeys[m][0][n] ** 2;
} else {
newLevel = monkeys[m][0][n] * op[1];
}
} else {
newLevel = monkeys[m][0][n] + op[1];
}
newLevel = newLevel % COMMON
const pass = newLevel % (test[0]) == 0 ? true : false;
monkeys[pass ? test[1] : test[2]][0].push(newLevel);
}
monkeys[m][0] = [];
}
}
counts = monkeys.map(m => m[3]);
counts.sort(function(a, b) {
return b - a;
});
console.log(counts[0] * counts[1]);
// functions