You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.3 KiB
55 lines
1.3 KiB
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);
|
|
|