answer2 = {
const opcodes = [];
for (const [opc, value] of input) {
opcodes.push([opc, value]);
}
const run = opcodes => {
let acc = 0;
let ip = 0;
let prevIp = 0;
let visited = new Set();
const nopsnjumps = [];
do {
visited.add(ip);
const [opc, value] = opcodes[ip];
prevIp = ip;
switch (opc) {
case "acc":
acc += value;
ip++;
break;
case "jmp":
nopsnjumps.push(ip);
ip += value;
break;
case "nop":
nopsnjumps.push(ip);
ip++;
break;
default:
return "error";
}
} while (ip < opcodes.length && !visited.has(ip));
return [acc, ip, prevIp, nopsnjumps];
};
const nopsnjumps = run(opcodes)[3];
for (const location of nopsnjumps) {
opcodes[location][0] = opcodes[location][0] === "nop" ? "jmp" : "nop";
const [acc, ip, prevIp, _nopsnjumps] = run(opcodes);
if (ip >= opcodes.length) return acc;
opcodes[location][0] = opcodes[location][0] === "nop" ? "jmp" : "nop";
}
}