You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.0 KiB
JavaScript

4 years ago
const fs = require("fs");
const inputFileName = "input";
async function main() {
const input = await fs.promises.readFile(inputFileName, "utf-8");
const machine = input.split(",").map((code) => parseInt(code));
machine[1] = 12;
machine[2] = 2;
for (let noun = 0; noun < 100; noun++) {
for (let verb = 0; verb < 100; verb++) {
machine[1] = noun;
machine[2] = verb;
if (intMachine(machine.slice()) == 19690720) {
console.log(100 * noun + verb);
process.exit();
}
}
}
}
function intMachine(machine) {
let curIdx = 0;
let opCode = machine[curIdx];
while (opCode !== 99) {
const val1 = machine[machine[curIdx + 1]];
const val2 = machine[machine[curIdx + 2]];
const register = machine[curIdx + 3];
if (opCode === 1) {
machine[register] = val1 + val2;
} else if (opCode === 2) {
machine[register] = val1 * val2;
} else {
throw Error("invalid opcode");
}
curIdx += 4;
opCode = machine[curIdx];
}
return machine[0];
}
main();