-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem8b.js
49 lines (47 loc) · 1.12 KB
/
problem8b.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const fs = require('fs');
const data = fs.readFileSync('input8.txt', 'utf8').split('\n').map(line => line.trim()).filter(line => line.length);
const program = data.map(line => {
const [ dummy, opcode, value ] = line.match(/^(\w+) ([+-]\d+)/);
return { opcode, value: parseInt(value) };
});
console.log(solve());
function solve() {
let poked = -1;
while(true) {
console.log(poked);
for (let poke = poked + 1; (poke < program.length); poke++) {
if (program[poke].opcode === 'jmp') {
program[poke].opcode = 'nop';
poked = poke;
break;
}
}
const visited = [];
let acc = 0;
let pc = 0;
while (true) {
if (pc === program.length) {
return acc;
}
if (visited[pc]) {
break;
}
visited[pc] = true;
switch (program[pc].opcode) {
case 'nop':
pc++;
break;
case 'acc':
acc += program[pc].value;
pc++;
break;
case 'jmp':
pc += program[pc].value;
break;
}
}
if (poked >= 0) {
program[poked].opcode = 'jmp';
}
}
}