69 lines
1.3 KiB
JavaScript
69 lines
1.3 KiB
JavaScript
const fs = require('fs');
|
|
|
|
//const inputArray = fs.readFileSync('sample.txt').toString().split("\n");
|
|
const inputArray = fs.readFileSync('input.txt').toString().split("\n");
|
|
|
|
// Part One
|
|
|
|
let x = 1;
|
|
let cycle = 0;
|
|
let samples = [];
|
|
|
|
for (i in inputArray) {
|
|
cycle++;
|
|
getSample();
|
|
const contents = inputArray[i].split(" ");
|
|
const instruction = contents[0];
|
|
if (instruction === 'addx') {
|
|
cycle++;
|
|
getSample();
|
|
x += parseInt(contents[1], 10);
|
|
}
|
|
}
|
|
|
|
const countedSamples = samples.slice(0, 7);
|
|
console.log(countedSamples.reduce((partialSum, a) => partialSum + a, 0));
|
|
|
|
|
|
// Part Two
|
|
|
|
x = 1;
|
|
cycle = 0;
|
|
let pixels = [];
|
|
|
|
for (i in inputArray) {
|
|
cycle++;
|
|
setPixel();
|
|
const contents = inputArray[i].split(" ");
|
|
const instruction = contents[0];
|
|
if (instruction === 'addx') {
|
|
cycle++;
|
|
setPixel();
|
|
x += parseInt(contents[1], 10);
|
|
}
|
|
}
|
|
|
|
const screen = [];
|
|
for (let i = 0; i < 6; i++) {
|
|
const line = pixels.slice(i * 40, (i + 1) * 40).join('');
|
|
screen.push(line)
|
|
}
|
|
console.log(screen);
|
|
|
|
// functions
|
|
|
|
function getSample() {
|
|
if (cycle === 20 || (cycle - 20) % 40 === 0) {
|
|
samples.push(cycle * x);
|
|
}
|
|
}
|
|
|
|
function setPixel() {
|
|
const position = cycle % 40;
|
|
if (position >= x && position <= x + 2) {
|
|
pixels.push('#');
|
|
} else {
|
|
pixels.push('.');
|
|
}
|
|
}
|