lluque

AoC day 12

Dec 13th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.04 KB | None | 0 0
  1. package day12
  2.  
  3. import scala.io.Source
  4. import scala.collection.mutable
  5.  
  6. object Prog {
  7.  
  8.   val registry = mutable.Map[Char, Int]('a' -> 0, 'b' -> 0, 'c' -> 0, 'd' -> 0)
  9.  
  10.   abstract class Instruction {
  11.     def exec: Int
  12.   }
  13.  
  14.   class Jump(cmd: String) extends Instruction {
  15.     val a: AnyVal = {
  16.       val operand = (cmd split ' ' slice (1, 2)).mkString
  17.       if (operand.forall(_.isDigit)) operand.toInt else operand.head
  18.     }
  19.     val b: Int = cmd.split(' ').last.toInt
  20.     override def exec = a match {
  21.       case i: Int => if (i > 0) b else 1
  22.       case c: Char => if (registry(c) > 0) b else 1
  23.     }
  24.   }
  25.  
  26.   class Copy(cmd: String) extends Instruction {
  27.     val a: AnyVal = {
  28.       val operand = (cmd split ' ' slice (1, 2)).mkString
  29.       if (operand.forall(_.isDigit)) operand.toInt else operand.head
  30.     }
  31.     val b: Char = (cmd split ' ').last.head
  32.     override def exec = a match {
  33.       case i: Int =>
  34.         registry(b) = i
  35.         1
  36.       case c: Char =>
  37.         registry(b) = registry(c)
  38.         1
  39.       }
  40.   }
  41.  
  42.   class Inc(cmd: String) extends Instruction {
  43.     val a: Char = cmd.last
  44.     override def exec = {
  45.       registry(a) += 1
  46.       1
  47.     }
  48.   }
  49.  
  50.   class Dec(cmd: String) extends Instruction {
  51.     val a: Char = cmd.last
  52.     override def exec = {
  53.       registry(a) -= 1
  54.       1
  55.     }
  56.   }
  57.  
  58.   def parse(s: String): Instruction = s match {
  59.     case s if s.startsWith("jnz") => new Jump(s)
  60.     case s if s.startsWith("cpy") => new Copy(s)
  61.     case s if s.startsWith("inc") => new Inc(s)
  62.     case s if s.startsWith("dec") => new Dec(s)
  63.   }
  64.  
  65.   def exec(xs: List[String]): Any = {
  66.     var p = 0
  67.     while (p < xs.length) {
  68.       p += parse(xs(p)).exec
  69.     }
  70.   }
  71.  
  72.   def run = {
  73.       def instructions = Source.fromFile("day12.txt").getLines.toList
  74.       // part 1
  75.       exec(instructions.map(_.trim))
  76.       println(registry('a'))
  77.       // part 2
  78.       registry.keys.foreach(k => if (k != 'c') registry(k) = 0 else registry(k) = 1)
  79.       exec(instructions.map(_.trim))
  80.       println(registry('a'))
  81.   }
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment