Skip to content

Instantly share code, notes, and snippets.

@pedromcunha
Created December 10, 2019 06:17
Show Gist options
  • Save pedromcunha/b03fae0f75f863d2743a1d13ee034e2f to your computer and use it in GitHub Desktop.
Save pedromcunha/b03fae0f75f863d2743a1d13ee034e2f to your computer and use it in GitHub Desktop.
const program = [1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,19,5,23,1,23,9,27,2,27,6,31,1,31,6,35,2,35,9,39,1,6,39,43,2,10,43,47,1,47,9,51,1,51,6,55,1,55,6,59,2,59,10,63,1,6,63,67,2,6,67,71,1,71,5,75,2,13,75,79,1,10,79,83,1,5,83,87,2,87,10,91,1,5,91,95,2,95,6,99,1,99,6,103,2,103,6,107,2,107,9,111,1,111,5,115,1,115,6,119,2,6,119,123,1,5,123,127,1,127,13,131,1,2,131,135,1,135,10,0,99,2,14,0,0]
function getOpCodeValues(program, i) {
const valuePos1 = program[i + 1]
const valuePos2 = program[i + 2]
const outputPos = program[i + 3]
return [program[valuePos1], program[valuePos2], outputPos]
}
for (var i = 0; i < program.length; i += 4) {
let code = program[i]
if (code === 1) {
const values = getOpCodeValues(program, i)
program[values[2]] = values[0] + values[1]
} else if (code === 2) {
const values = getOpCodeValues(program, i)
program[values[2]] = values[0] * values[1]
} else if (code === 99) {
break;
} else {
throw 'Unexpected code found! Code: ' + code + ' Index: ' + i
}
}
console.log(program)
@pedromcunha
Copy link
Author

pedromcunha commented Dec 25, 2019

Part two

class IntCodeMachine {
  getOpCodeValues(program, i) {
    const valuePos1 = program[i + 1]
    const valuePos2 = program[i + 2] 
    const outputPos = program[i + 3]
    return [program[valuePos1], program[valuePos2], outputPos]
  }

  read(program) {
    for (var i = 0; i < program.length; i += 4) {
      let code = program[i]
      if (code === 1) {
        const values = this.getOpCodeValues(program, i)
        program[values[2]] = values[0] + values[1]
      } else if (code === 2) {
        const values = this.getOpCodeValues(program, i)
        program[values[2]] = values[0] * values[1]
      } else if (code === 99) {
        break;
      } else {
        throw 'Unexpected code found! Code: ' + code + ' Index: ' + i
      }
    }
    return program
  }
}

let machine = new IntCodeMachine()
for (var noun = 0; noun < 99; noun++) {
  for (var verb = 0; verb < 99; verb++) {
    const program  = [...originalProgram]
    program[1] = noun
    program[2] = verb
    const result = machine.read(program)
    if (result[0] === 19690720) {
      console.log("Result found!", noun, verb)
      break;
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment