IntCode.scala 762 Bytes
Newer Older
David's avatar
David committed
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
package is.kow.adventofcode._2019

import scala.annotation.tailrec

class IntCode(ops: List[Int]) {
  private final val ADD = 1
  private final val MULT = 2
  private final val END = 99

  def execute(): List[Int] = {

    @tailrec def process(acc: List[Int], opCount: Int): List[Int] = {
      acc.drop(opCount * 4) match {
        case ADD :: in1 :: in2 :: dest :: xs =>
          val result = acc(in1) + acc(in2)
          process(acc.updated(dest, result), opCount + 1)
        case MULT :: in1 :: in2 :: dest :: xs =>
          val result = acc(in1) * acc(in2)
          process(acc.updated(dest, result), opCount + 1)
        case END :: xs =>
          acc
        case _ => throw new Exception("Unknown opcode")
      }
    }

    process(ops, 0)
  }

}