lluque

AoC day 10

Dec 12th, 2016
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.28 KB | None | 0 0
  1. import scala.io.Source
  2.  
  3.  
  4. object day10 {
  5.  
  6.   trait handler {
  7.     val inventory = collection.mutable.SortedSet[Int]()
  8.   }
  9.  
  10.   case class Bot(id: Int) extends handler {
  11.     var lowReceiver: handler = _
  12.     var highReceiver: handler = _
  13.   }
  14.  
  15.   case class Output(id: Int) extends handler
  16.  
  17.   def amountBots(s: String): Int = {
  18.     ("bot (\\d+)".r.findAllIn(s).matchData map (m => m.group(1).toInt)).toList.sorted.last
  19.   }
  20.   def amountOutputs(s: String): Int = {
  21.     ("output (\\d+)".r.findAllIn(s).matchData map (m => m.group(1).toInt)).toList.sorted.last
  22.   }
  23.  
  24.   val instructions = Source.fromFile("day10.txt").getLines.toList
  25.  
  26.   val bots = (0 to amountBots(instructions.mkString)).map(Bot)
  27.   val outputs = (0 to amountOutputs(instructions.mkString)).map(Output)
  28.   val undoneChips = collection.mutable.Set[Int]()
  29.  
  30.   // Init, take everything from chip source + configure each bot
  31.   instructions.foreach {
  32.     case x if x startsWith "value" =>
  33.       val value = (x split ' ' drop 1).head.toInt
  34.       val sink = (x split ' ').last.toInt
  35.       bots(sink).inventory += value
  36.       undoneChips += value
  37.     case x if x startsWith "bot" =>
  38.       val fromId = (x split ' ' drop 1).head.toInt
  39.       val lowType = (x split ' ' drop 5).head
  40.       val lowId = (x split ' ' drop 6).head.toInt
  41.       val highType = (x split ' ' takeRight 2).head
  42.       val highId = (x split ' ').last.toInt
  43.       bots(fromId).lowReceiver = if (lowType == "bot") bots(lowId) else outputs(lowId)
  44.       bots(fromId).highReceiver = if (highType == "bot") bots(highId) else outputs(highId)
  45.   }
  46.  
  47.   // Action loop
  48.   while (undoneChips.nonEmpty) {
  49.     for {
  50.       bot <- bots.filter(_.inventory.size >= 2)
  51.       low = bot.inventory.head
  52.       hi = bot.inventory.last
  53.     } yield {
  54.       if (bot.inventory(61) && bot.inventory(17))
  55.         println(s"Part 1: ${bot.id}")
  56.  
  57.       def give(to: handler, value: Int): Any = to match {
  58.         case bot: Bot => bot.inventory += value
  59.         case output:
  60.           Output => output.inventory += value
  61.           undoneChips.remove(value)
  62.       }
  63.  
  64.       give(bot.lowReceiver, low)
  65.       give(bot.highReceiver, hi)
  66.       bot.inventory.remove(low)
  67.       bot.inventory.remove(hi)
  68.     }
  69.   }
  70.  
  71.   println(s"Part 2: ${(0 to 2 map (n => outputs(n).inventory.head)).product}")
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment