Advent of Code 2022: Day 10

CPU & CRT line rendering🤖

by Amy L

HTML

<link rel="stylesheet" href="https://adventofcode.com/static/style.css?30">
<h1><a href="https://adventofcode.com/2022/day/10" target="_blank">Day 10</a></h1>
<diV class="puzzle-input">
  <label for="INPUT_DATA">Input</label>
  <textarea id="INPUT_DATA" autocomplete="off" placeholder="paste your input here" rows="7" cols="50"></textarea>
</diV>
<dl>
<dt>Part 1</dt>
  <dd>
    <label>Answer:
      <input type="text" id="answer1" readonly />
    </label>
  </dd>
  
  <dt>Part 2</dt>
  <dd>
    <label>Answer:
    <textarea id="answer2" readonly rows="6" cols="40"></textarea>
    </label>
  </dd>
</dl>

JavaScript 1.7

const OPERATIONS = {
	NOOP: 'noop', 
  ADD_X: 'addx'
};
const PIXELS = {
	LIT: '#',
  DARK: ' '
};
const EXECUTORS = {
	// record each operation and register X value to the STATE.log
  logRegisterX: (STATE, instruction) => {
    STATE.log.push({
      x: STATE.registers.x,
      operation: instruction.operation,
      operand: instruction.operand
    });
  },
  // light the appropriate pixel for each operation to the STATE.screen
  draw: (STATE, instruction) => {
    console.log(`During cycle ${STATE.cycle+1}:\t\tCRT draws pixel in position ${STATE.drawX}`);

    lightPixel(STATE.line, STATE.sprite, STATE.drawX);

    console.log(`Current CRT row:\t\t${STATE.line.join('')}`);
    console.log(`End of cycle ${STATE.cycle+1}:\t\tfinish executing ${instruction.operation} ${instruction.operand} (Register X is now ${STATE.registers.x})`);

    STATE.sprite = positionSprite(STATE.registers, STATE.line.length);

    checkLineComplete(STATE);
    STATE.cycle++;
  }
};
function Day10(input) {
  function solvePart1(instructions) {
    const STATE = executeInstructions(instructions, EXECUTORS.logRegisterX, {
      log: [],
      registers: {
        x: 1
      }
    });
    const total = [20, 60, 100, 140, 180, 220].reduce((subtotal, cycle) => {
    	const signalStrength = calculateSignalStrength(cycle, STATE.log);
    	return subtotal + signalStrength;
    }, 0);
    return total;
  }
  function solvePart2(instructions) {
  	const width = 40;
    const registers = {
      x: 1
    };
    const STATE = executeInstructions(instructions, EXECUTORS.draw, {
      registers,
      cycle: 0,
      drawX: 0,
      screen: [],
      line: initializeLine(width),
      sprite: positionSprite(registers, width)
    });
  	return STATE.screen.join('\n');
  }
  
  const instructions = parseInstructions(input);
  const part1 = solvePart1(instructions);
  const part2 = solvePart2(instructions);
  return {part1,  part2};
  
}
document.addEventListener('DOMContentLoaded', () => {
 ...