adventofcode2022/day10/solution.ts
2022-12-11 14:57:06 -05:00

76 lines
1.4 KiB
TypeScript

import { readFileSync } from 'fs';
import { join } from 'path';
const fileString = readFileSync(join(__dirname, "input"), 'utf-8');
var rows = fileString.split("\n");
rows = rows.map(val => {
return val.trim();
});
rows = rows.filter(val => {
return val.length > 0;
});
// Parse out the instruction into "micro-ops"
var cmds = [];
for (const row of rows) {
const inst = row.split(" ");
switch(inst[0]) {
case "noop":
cmds.push(inst);
break;
case "addx":
cmds.push(["noop"]);
cmds.push(inst);
break;
}
}
console.log(cmds);
console.log(cmds.length);
const breakpoints = [20, 60, 100, 140, 180, 220];
// Start the VM
var sums = [];
var reg_X = 1;
var crt_pos = 1;
for (var i = 0; i < cmds.length; i++) {
const cmd = cmds[i];
if (breakpoints.indexOf(i + 1) > -1) {
sums.push(reg_X * (i + 1));
}
switch(cmd[0]) {
case "noop":
break;
case "addx":
reg_X += +cmd[1];
break;
}
// Do TV drawing
if (crt_pos > 40) {
process.stdout.write("\n");
crt_pos = 1;
}
if (crt_pos >= (reg_X - 1) && (crt_pos <= (reg_X + 1))) {
//console.log("cursor: ", crt_pos, " reg ", reg_X, i, cmd);
process.stdout.write("#");
} else {
//console.log("cursor: ", crt_pos, " reg ", reg_X, crt_pos > reg_X - 1, crt_pos < reg_X + 1, cmd);
process.stdout.write(".");
}
crt_pos += 1;
}
process.stdout.write("\n");
console.log(sums.reduce((a, b) => {
return a + b;
}));