Skip to content

Instantly share code, notes, and snippets.

@rofr
Created December 2, 2019 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rofr/95c257ff6b7087c091d7fc4fb293c293 to your computer and use it in GitHub Desktop.
Save rofr/95c257ff6b7087c091d7fc4fb293c293 to your computer and use it in GitHub Desktop.
AOC 2019 Day2
function op(mem, ip) {
if (mem[ip] == 99) return -1
let lv = mem[mem[ip+1]]
let rv = mem[mem[ip+2]]
if (mem[ip] == 1) mem[mem[ip+3]] = lv + rv
else if (mem[ip] == 2) mem[mem[ip+3]] = lv * rv
else throw "Invalid op code"
return ip + 4
}
let mem = document.body.textContent.split(",").map(m => parseInt(m))
function part1() {
let ip = 0
mem[1] = 12
mem[2] = 2
while (ip >= 0) {
ip = op(mem,ip)
}
console.log("Answer part 1:", mem[0])
}
part1()
// --------------- PART 2 --------------------------
function run(mem, noun, verb) {
let ip = 0
mem = JSON.parse(JSON.stringify(mem))
mem[1] = noun
mem[2] = verb
while (ip >= 0) {
ip = op(mem,ip)
}
return mem[0]
}
function part2() {
for(let a = 0; a < mem.length; a++) {
for (let b = 0; b < mem.length; b++) {
let result = run(mem,a,b)
if (result == 19690720) {
console.log("Answer part 2:", 100 * a + b)
}
}
}
}
mem = document.body.textContent.split(",").map(m => parseInt(m))
part2()
/*
1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,6,19,23,2,23,6,27,1,5,27,31,1,31,9,35,2,10,35,39,1,5,39,43,2,43,10,47,1,47,6,51,2,51,6,55,2,55,13,59,2,6,59,63,1,63,5,67,1,6,67,71,2,71,9,75,1,6,75,79,2,13,79,83,1,9,83,87,1,87,13,91,2,91,10,95,1,6,95,99,1,99,13,103,1,13,103,107,2,107,10,111,1,9,111,115,1,115,10,119,1,5,119,123,1,6,123,127,1,10,127,131,1,2,131,135,1,135,10,0,99,2,14,0,0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment