Day 10: Cathode-Ray Tube
**
There's some sort of signal defining commands to execute that add and subtract values. In Part I we multiply the value at certain cycles. In Part II we use the value as the position of a sprite and create an imag out of it.
Journal
I don't remember this being too tough. Mostly just understanding what it was asking. I think there was some figuring out what the "sprite in the 3 pixels" thing was all about.
After understanding what was going on it was pretty straight forward.
It was cool to have an actual output that wasn't just a number though.
Relevant Code
const TARGET_CYCLES = [220, 180, 140, 100, 60, 20];export const getSignalStrengths = (signal: string) => {const commands = signal.split("\n");let sum = 0;let cycle = 0;let x = 1;let currentCycleTarget = TARGET_CYCLES.pop();commands.forEach((command) => {let addVal = 0;if (command === "noop") {cycle++;} else {cycle += 2;const [_, val] = command.split(" ");addVal = +val;}if (cycle >= (currentCycleTarget ?? 0)) {sum += (currentCycleTarget ?? 0) * x;currentCycleTarget = TARGET_CYCLES.pop();}x += addVal;});return sum;};export const getScreenContent = (signal: string) => {const commands = signal.split("\n");let output = "";let currentCommand = commands.shift();let currentState = "addx";let spritePosition = 1;for (let cycle = 1; cycle < 240; cycle++) {const position = (cycle - 1) % 40;output +=spritePosition - 1 <= position && position <= spritePosition + 1? "#": ".";if (cycle % 40 === 0) {output += "\n";}if (currentCommand === "noop") {currentCommand = commands.shift();} else if (currentState === "addx") {currentState = "addx2";} else {const [_, val] = currentCommand!.split(" ");spritePosition += +val;currentState = "addx";currentCommand = commands.shift();}}return output;};
Output
Test Signal
- Part I: 13140 is an arbitrary value that represents "signal strength" (5 ms)
- Part II:
##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######....
0 ms)
Real Signal
- Part I: 12640 is an arbitrary value that represents "signal strength" (0 ms)
- Part II:
####.#..#.###..####.#....###....##.###.. #....#..#.#..#....#.#....#..#....#.#..#. ###..####.###....#..#....#..#....#.#..#. #....#..#.#..#..#...#....###.....#.###.. #....#..#.#..#.#....#....#.#..#..#.#.#.. ####.#..#.###..####.####.#..#..##..#..#
(0 ms)