repl.it
@Kognise/

AoC2019 2

Nodejs

Advent of Code is an Advent calendar of programming puzzles. https://adventofcode.com/2019/day/2

fork
loading
Files
  • index.js
  • inputs.js
index.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
const runComputer = (instructions) => {
  const memory = [ ...instructions ] // Make a copy so I can safely mutate
  let pointer = 0

  while (true) {
    const code = memory[pointer]

    const cell1 = memory[memory[pointer + 1]]
    const cell2 = memory[memory[pointer + 2]]

    if (code === 99) {
      return memory
    } else if (code === 1) {
      memory[memory[pointer + 3]] = cell1 + cell2
    } else if (code === 2) {
      memory[memory[pointer + 3]] = cell1 * cell2
    }

    pointer += 4
  }
}

const inputs = require('./inputs')
const partTwoResult = 19690720

const result1 = runComputer(inputs)
console.log('Part one:', result1[0])

let solved = false
for (let a = 0; a < 1000; a++) {
  for (let b = 0; b < 1000; b++) {
    inputs[1] = a
    inputs[2] = b
    
    const result2 = runComputer(inputs)

    if (result2[0] === partTwoResult) {
      solved = true
      console.log('Part two:', 100 * result2[1] + result2[2])
      break
    }
  }
  if (solved) break
}