import { readFileSync } from 'node:fs'; const input = readFileSync('input', 'utf-8'); const cycles = input .split('\n') .filter(line => line) .flatMap((() => { let x = 1; return (line) => { if (line.startsWith('noop')) { return [x]; } if (line.startsWith('addx')) { const add = parseInt(line.substring(5)); if (isNaN(add)) { throw new Error('Invalid value for addx'); } const result = [x, x]; x += add; return result; } }; })()); const sumOfSignalStrengths = [20, 60, 100, 140, 180, 220] .map(c => { const x = cycles[c - 1]; const strength = c * x; return strength; }) .reduce((total, strength) => total + strength); console.log( `The sum of observed signal strengths is: ${sumOfSignalStrengths}` ); const render = cycles .map((x, c) => { const scanPos = c % 40; return [x - 1, x, x + 1].some(pixelPos => pixelPos === scanPos); }) .reduce((display, pixelVisible, c) => { const scanLine = Math.floor(c / 40); if (!display[scanLine]) { display.push([]); } display[scanLine].push(pixelVisible ? '#' : ' '); return display; }, []) .map(scanLine => scanLine.join('')) .join('\n'); console.log('Display output:'); console.log(render);