Published
Edited
Dec 10, 2020
Insert cell
Insert cell
Insert cell
answer1 = {
let acc = 0;
let ip = 0; // instruction pointer
let prevIp = 0;
let visited = new Set();
do {
visited.add(ip);
const [opc, value] = input[ip];
prevIp = ip;
switch (opc) {
case "acc":
acc += value;
ip++;
break;
case "jmp":
ip += value;
break;
case "nop":
ip++;
break;
default:
return "error";
}
} while (!visited.has(ip));
return [acc, ip, prevIp];
}
Insert cell
Insert cell
answer2 = {
const opcodes = [];
// let's copy the input so we don't accidentally mutate it
for (const [opc, value] of input) {
opcodes.push([opc, value]);
}

const run = opcodes => {
let acc = 0;
let ip = 0; // instruction pointer
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];
};
// The location of the jumps/nops in the unmodified code
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";
}
}
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more