Published
Edited
Dec 10, 2019
Importers
Insert cell
Insert cell
function run (state) {
const {memory, pointer = 0, input = 1, outputs = []} = state
let mem = memory.slice().split(",").map(Number)
const opcode = String(mem[pointer]).padStart(5,"0")
const command = +opcode.substring(3)
//base
if(command===99 || pointer >= mem.length - 1) { return state }
//recursive
if(command===3) {
mem[mem[pointer+1]] = input
return run({memory: mem.join(","), pointer: pointer+2, input: input, outputs: outputs})
}
let param1 = +opcode[2]===0 ? mem[mem[pointer+1]] : mem[pointer+1],
param2 = +opcode[1]===0 ? mem[mem[pointer+2]] : mem[pointer+2]
if(command===4)
return run({memory: mem.join(","), pointer: pointer+2, input: input, outputs: outputs.concat(param1)})
if(command==5)
return run({memory: mem.join(","), pointer: param1!=0? param2 : pointer+3, input: input, outputs: outputs})
if(command==6)
return run({memory: mem.join(","), pointer: param1==0? param2 : pointer+3, input: input, outputs: outputs})
if(command==1) mem[mem[pointer+3]] = param1 + param2
if(command==2) mem[mem[pointer+3]] = param1 * param2
if(command==7) mem[mem[pointer+3]] = param1 < param2 ? 1 : 0
if(command==8) mem[mem[pointer+3]] = param1 == param2 ? 1 : 0
return run({memory: mem.join(","), pointer: pointer+4, input: input, outputs: outputs})
}
Insert cell
intcomputer = _d => _i => {
const outputs = run({memory: _d, input: _i}).outputs
for(let i = 0; i < outputs.length - 1; i++) if(outputs[i]!==0) return "nonzero diagnostic code returned"
return outputs.pop()
}
Insert cell
run({memory: day2Data}).memory.split(",")[0] // verify using the original (day 2) challenge input
Insert cell
[7,8,9].map(intcomputer(testCompare8)) // test program from instructions
Insert cell
intcomputer(data)(1) // part 1
Insert cell
intcomputer(data)(5) // part 2
Insert cell
Insert cell
Insert cell
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