Day 8
This commit is contained in:
61
08/part2.js
Normal file
61
08/part2.js
Normal file
@@ -0,0 +1,61 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
});
|
Reference in New Issue
Block a user