Public
Edited
Dec 11, 2022
Insert cell
Insert cell
Insert cell
function execute(program) {
let currentCycle = 1;
let cycles = [];
let x = 1;
for (let instruction of program) {
if (instruction.cycles === 1) {
cycles.push({
cycle: currentCycle,
xDuring: x,
xAfter: x + instruction.incr
});
} else {
cycles.push({ cycle: currentCycle, xDuring: x, xAfter: x });
cycles.push({
cycle: currentCycle + 1,
xDuring: x,
xAfter: x + instruction.incr
});
}
x += instruction.incr;
currentCycle += instruction.cycles;
}
return cycles;
}
Insert cell
execLog = execute(dataset)
Insert cell
interestingSignalStrengths = {
let interestingSteps = [];
let i = 0;
while (20 + i * 40 < execLog.length) {
interestingSteps.push(20 + i * 40);
i++;
}
return execLog
.filter((cycle) => interestingSteps.includes(cycle.cycle))
.map((cycle) => cycle.cycle * cycle.xDuring);
}
Insert cell
_.sum(interestingSignalStrengths)
Insert cell
Insert cell
{
let currentPixel = 0;
let pixels = ["\n"];
for (let cycle of execLog) {
if (Math.abs(cycle.xDuring - currentPixel) <= 1) pixels.push("#");
else pixels.push(".");
if ((currentPixel + 1) % 40 === 0) pixels.push("\n");
currentPixel = (currentPixel + 1) % 40;
}
return pixels.join("");
}
Insert cell
Insert cell
function readInput(txt) {
return txt.split("\n").map((line) => {
if (line[0] === "n") return { cycles: 1, incr: 0 };
else {
let incrVal = parseInt(line.split(" ")[1]);
return { cycles: 2, incr: incrVal };
}
});
}
Insert cell
Insert cell
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