git-subtree-dir: 2020 git-subtree-mainline:ab8f135946
git-subtree-split:aaabfa90c9
62 lines
1.1 KiB
JavaScript
62 lines
1.1 KiB
JavaScript
const fs = require('fs');
|
|
|
|
function parseLine(line) {
|
|
let [ op, offset ] = line.split(' ');
|
|
|
|
return { op: op, offset: Number(offset), visited: false };
|
|
}
|
|
|
|
function run(program) {
|
|
let acc = 0;
|
|
let pc = 0;
|
|
|
|
while(true) {
|
|
if (pc == program.length) {
|
|
return acc;
|
|
};
|
|
|
|
let insn = program[pc];
|
|
if (insn.visited) {
|
|
return undefined;
|
|
};
|
|
|
|
insn.visited = true;
|
|
|
|
switch (insn.op) {
|
|
case 'nop':
|
|
pc++;
|
|
break;
|
|
case 'jmp':
|
|
pc = pc + insn.offset;
|
|
break;
|
|
case 'acc':
|
|
acc = acc + insn.offset;
|
|
pc++;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
fs.readFile('input', (err, data) => {
|
|
if (err) throw err;
|
|
let program = data.toString().trim().split("\n").map( parseLine ).flat();
|
|
|
|
for(i=0; i<program.length; i++) {
|
|
let copy = JSON.parse(JSON.stringify(program))
|
|
let insn = copy[i];
|
|
|
|
if (insn.op == 'nop') {
|
|
insn.op = 'jmp';
|
|
} else if (insn.op == 'jmp') {
|
|
insn.op = 'nop';
|
|
} else {
|
|
continue; // If we don't make any changes, the program can't terminate
|
|
}
|
|
|
|
if (result = run(copy)) {
|
|
console.log(result);
|
|
return;
|
|
}
|
|
}
|
|
});
|