Public
Edited
Dec 11, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
testInstructions = parseProgram(test)
Insert cell
function parseProgram(input) {
return input.trim().split("\n").map(parseInstruction);
}
Insert cell
function parseInstruction(input) {
const [command, value] = input.split(/\s+/);
return {command, value: value ? +value : undefined};
}
Insert cell
testStates = [...executeInstructions(testInstructions)]
Insert cell
Insert cell
function* executeInstructions(instructions) {
let X = 1;
let cycle = 0;

for (const {command, value} of instructions) {
let delay;

function currentState(phase) {
return {cycle, phase, X, command, value, delay};
}
switch (command) {
case "noop": delay = 1; break;
case "addx": delay = 2; break;
default: throw new Error(`unknown command: ${command}`);
}

++cycle;
yield currentState("start");

while (--delay) {
yield currentState("end");
++cycle;
yield currentState("start");
}

switch (command) {
case "noop": break;
case "addx": X += value; break;
default: throw new Error(`unknown command: ${command}`);
}

yield currentState("end");
}
}
Insert cell
Insert cell
largeTestInstructions = parseProgram(largeTest)
Insert cell
largeTestEvaluation = [...executeInstructions(largeTestInstructions)]
Insert cell
sumSignalStrength(largeTestEvaluation)
Insert cell
function sumSignalStrength(states, cycles = [20, 60, 100, 140, 180, 220]) {
let sum = 0;
cycles = new Set(cycles);
for (const {cycle, phase, X} of states) {
if (phase === "start" && cycles.has(cycle)) {
sum += X * cycle;
}
}
return sum;
}
Insert cell
Insert cell
instructions = parseProgram(input)
Insert cell
states = [...executeInstructions(instructions)]
Insert cell
Insert cell
sumSignalStrength(states)
Insert cell
largeTestInstructions
Insert cell
Insert cell
renderCrt(largeTestInstructions)
Insert cell
function* renderCrt(instructions) {
let crt = "";
let i = 0;
yield crt;
for (const {cycle, phase, X} of executeInstructions(instructions)) {
if (phase === "start") {
if (i === 0) crt += "\n";
crt += Math.abs(X - i) < 2 ? "#" : ".";
yield crt;
i = (i + 1) % 40;
}
}
}
Insert cell
renderCrt(instructions)
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