Public
Edited
Dec 10, 2022
1 fork
Importers
1 star
Insert cell
Insert cell
Insert cell
parse = aoc.lines((d) => {
const [cmd, ...args] = d.split(" ");
return { cmd, args };
})
Insert cell
function part1(input) {
let sum = 0;
let targetCycles = d3.range(20, 221, 40);
for (let state of computer(input)) {
if (targetCycles.includes(state.cycle)) {
sum += state.cycle * state.x;
}
}
return sum;
}
Insert cell
function part2(input) {
return detectLetters(
d3.map(computer(input), ({ cycle, x }) =>
Math.abs(((cycle - 1) % 40) - x) <= 1 ? "#" : " "
)
);
}
Insert cell
function* computer(input) {
let cycle = 1;
let x = 1;
for (const op of input) {
yield { cycle: cycle++, x };
if (op.cmd === "addx") {
yield { cycle: cycle++, x };
x += +op.args[0];
} else if (op.cmd !== "noop") {
throw new Error(`unknown cmd ${op.cmd}`);
}
}
yield { cycle, x };
}
Insert cell
Insert cell
Insert cell
detectLetters = (grid) => {
function* inner() {
const at = (x, y) => grid[x + y * 40];
for (const letter of d3.range(0, 8)) {
let acc = 0;
for (const y of d3.range(0, 6)) {
for (const x of d3.range(letter * 5, letter * 5 + 4)) {
acc <<= 1;
if (at(x, y) === "#") acc |= 0b1;
}
}
let found = alphabet.find((d) => d[1] === acc);
if (found) {
yield found[0];
} else {
throw new Error(`no match for pattern 0b${acc.toString(2)}`);
}
}
}

return Array.from(inner()).join("");
}
Insert cell
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