Skip to content

Instantly share code, notes, and snippets.

@tminard
Created December 3, 2019 16:13
Show Gist options
  • Save tminard/0ffbefc16a6062caf4db8d12c22dc45c to your computer and use it in GitHub Desktop.
Save tminard/0ffbefc16a6062caf4db8d12c22dc45c to your computer and use it in GitHub Desktop.
advent-of-code-2019
import scala.io.Source
var TAPE = Array.empty[Int]
// Instructions
val OP_ADD = 1
val OP_MUL = 2
val OP_END = 99
// Instruction Pointer
var TAPE_POS = 0
def add(): Int = {
val ADR_A = TAPE(TAPE_POS + 1) // Noun
val ADR_B = TAPE(TAPE_POS + 2) // Verb
val ADR_O = TAPE(TAPE_POS + 3)
TAPE(ADR_O) = TAPE(ADR_A) + TAPE(ADR_B)
3
}
def mult(): Int = {
val ADR_A = TAPE(TAPE_POS + 1) // Noun
val ADR_B = TAPE(TAPE_POS + 2) // Verb
val ADR_O = TAPE(TAPE_POS + 3)
TAPE(ADR_O) = TAPE(ADR_A) * TAPE(ADR_B)
3
}
def doop(op: Int): Int = op match {
case OP_ADD => add()
case OP_MUL => mult()
case OP_END => 0
}
def readprog() = {
println("TAPE has size " + TAPE.length)
println("Initial Program State: "+ TAPE.mkString(","))
println("--")
var CUR_OP = -1
while (CUR_OP != OP_END) {
CUR_OP = TAPE(TAPE_POS)
val params = doop(CUR_OP)
TAPE_POS += (params + 1)
}
println("Final Program State: " + TAPE.mkString(","))
}
def resetprog() = {
TAPE = Source.fromFile("input.txt").getLines().next.split(",").map(_.toInt)
TAPE_POS = 0
}
resetprog()
readprog()
val TARGET = 19690720 // Noun + verb
// breadth-first search; assumes value will exist
def findprog(noun : Int, candidates : Vector[Int]) : Int = {
for (verb <- candidates) {
resetprog()
TAPE(1) = noun
TAPE(2) = verb
readprog()
if (TAPE(0) == TARGET) return (100 * noun + verb)
}
val rest :+ first = candidates
findprog(first, rest)
}
val inputs = Vector.range(0, 100)
val candidates :+ noun : Vector[Int] = inputs
val answer = findprog(noun, candidates)
println("Part 2 answer: " + answer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment