Public
Edited
Dec 10, 2022
Insert cell
Insert cell
Insert cell
class VM {
x = 1;
signal = 0;
cycles = 0;
instructions = [];
delayed = {};
ptr = 0;

load(input) {
this.instructions = input.split("\n").map((l) => {
const tokens = l.split(" ");
if (tokens[0] === "noop") {
return tokens;
}
return [tokens[0], parseInt(tokens[1])];
});
}

step() {
this.cycles++;

if ("addx" === this.instructions[this.ptr][0]) {
this.cycles++;

// main phase

// end of cycle
this.x += this.instructions[this.ptr][1];
}
this.ptr++;
}

run() {
this.cycles = 0;

for (let i = 0; i < this.instructions.length; i++) {
this.step();
}

return this.x;
}
}
Insert cell
{
const vm = new VM();
vm.load(testInput1);
return vm.instructions;
}
Insert cell
{
const vm = new VM();
vm.load(testInput1);
return vm.run();
return vm.x;
}
Insert cell
Insert cell
{
const vm = new VM();
vm.load(testInput2);
vm.run();
return vm.signal;
}
Insert cell
{
const vm = new VM();
vm.load(testInput2);
do {
vm.step();
} while (vm.cycles < 60);
return JSON.stringify({
signal: vm.signal,
clock: vm.cycles,
x: vm.x
});

return vm.x;
}
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