Published
Edited
Dec 9, 2020
Insert cell
Insert cell
runAndGetAcc(exampleinput) // part 1 example
Insert cell
runAndGetAcc(input) // part 1 solution
Insert cell
findAccOfNonAbortingVariation(input) // part 2 solution
Insert cell
// String -> Number
runAndGetAcc = data => run(instructions(data)).acc
Insert cell
// Program -> {Bool, Number}
run = program => {
let op;
let register = 0;
for(let i = 0; ; ) {
if(i >= program.length) return {aborted: false, acc: register} // terminated correctly
op = program[i]
if(op[2]!=0) return {aborted: true, acc: register} // repeating instructions, inf loop
op[2] = i+1; // order this instruction was executed, like in the example
switch(op[0]) {
case "nop":
i++;
break;
case "acc":
register+= op[1];
i++;
break;
case "jmp":
i+=op[1];
break;
default:
console.log("bad opcode: " + op);
return null
break;
}
}
}
Insert cell
// String -> Number
findAccOfNonAbortingVariation = data => variations(instructions(data))
.map(run)
.filter(result => !result.aborted)[0] // one variation should have terminated correctly
.acc
Insert cell
// Program -> [Program]
variations = program => {
let vars = []
for(let i = 0; i < program.length; i++) {
if(!(program[i][0]=="nop" || program[i][0]=="jmp")) continue; // if op is not jmp or nop, go to next op
let clone = JSON.parse(JSON.stringify(program))
clone[i][0] = clone[i][0]=="jmp" ? "nop" : "jmp" // swap jmp and nop
vars.push(clone)
}
return vars
}
Insert cell
// String -> Program[[String opname, Number param, Number executionOrder = 0]]
instructions = data => data // String
.split("\n") // [String]
.map(op => op.split(" ")) // [[String, String]]
.map(op => {op[1] = Number(op[1]); return op}) // [[String, Number]]
.map(op => op.concat(0)) // [[String, Number, 0]]
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more