Published
Edited
Dec 9, 2020
Insert cell
Insert cell
Insert cell
function parseInput(source) {
return source.split('\n').map(l => {
const [op, arg] = l.split(' ');
return [op, parseInt(arg)];
});
}
Insert cell
class VM {
constructor(program) {
this.program = program;
this.accumulator = 0;
this.instructionPtr = 0;
this.seenAddrs = new Set();
this.terminated = false;
}

nop() {
this.instructionPtr++;
}

acc(val) {
this.accumulator += val;
this.instructionPtr++;
}

jmp(val) {
this.instructionPtr += val;
}

run() {
while (
!this.seenAddrs.has(this.instructionPtr) &&
this.instructionPtr !== this.program.length
) {
const [op, arg] = this.program[this.instructionPtr];
this.seenAddrs.add(this.instructionPtr);
this[op](arg);
}
this.terminated = this.instructionPtr === this.program.length;
return this.accumulator;
}
}
Insert cell
testVM = new VM( parseInput( testInput ) );
Insert cell
testVM.run();
Insert cell
Insert cell
Insert cell
{
const vm = new VM(parseInput(input));
return vm.run();
}
Insert cell
Insert cell
_ = require('lodash')
Insert cell
function part2(program) {
for (let i = 0; i < program.length; i++) {
let programCopy = _.cloneDeep(program);
if (programCopy[i][0] === 'nop') {
programCopy[i][0] = 'jmp';
} else if (programCopy[i][0] === 'jmp') {
programCopy[i][0] = 'nop';
}
const vm = new VM(programCopy);
// yield programCopy;
vm.run();
if (vm.terminated) {
return vm.accumulator;
}
}
}
Insert cell
part2(parseInput(testInput))
Insert cell
terminatingTestProgram = parseInput(testInput)
Insert cell
terminatingTestProgram[7][0] = 'nop';
Insert cell
terminatingTestVM = new VM( terminatingTestProgram );
Insert cell
terminatingTestVM.run()
Insert cell
part2(parseInput(input))
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more