Last active
December 8, 2020 19:51
-
-
Save DarkMio/c285eeedfb28a1568b35b7b9edee9b99 to your computer and use it in GitHub Desktop.
AoC 2020 VM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let parse = (entry) => { | |
const op = entry.match(/(?<op>.*) (?<value>.*)/).groups; | |
return { | |
cnt: 0, | |
op: op.op, | |
value: parseInt(op.value) | |
} | |
} | |
let runProgram = (program) => { | |
program.forEach(x => x.cnt = 0); | |
let stack = 0; | |
let accu = 0; | |
const cmd = { | |
"nop": (value) => stack += 1, | |
"acc": (value) => { accu += value; stack += 1; }, | |
"jmp": (value) => stack += value, | |
} | |
while(stack < program.length) { | |
const op = program[stack]; | |
if(op.cnt > 0) { throw accu; } | |
op.cnt += 1; | |
cmd[op.op](op.value); | |
} | |
return accu; | |
} | |
let fixProgram = (program) => { | |
const cmd = { "nop": "jmp", "jmp": "nop", "acc": "acc" }; | |
for(let i = 0; i < program.length; i++) { | |
const op = program[i]; | |
if(op.op == "acc") { continue; } | |
op.op = cmd[op.op]; | |
try { | |
const acc = runProgram(program); | |
return acc; | |
} catch { op.op = cmd[op.op]; } | |
} | |
} | |
const content = $0.textContent.split("\n"); | |
content.pop() | |
const program = content.map(parse); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment