Guest User

Advent of Code 2020 Day 8

a guest
Dec 8th, 2020
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.34 KB | None | 0 0
  1. import scala.io.Source
  2.  
  3. object Day8 extends App {
  4.   abstract class Instruction(var f:(() => Unit), var timesRun:Int = 0){
  5.     val originalF = f
  6.     def run() = {pc += 1;f(); timesRun += 1}
  7.     def switch() = ()
  8.     def restore() = f = originalF
  9.   }
  10.   case class Acc(parameter:Int) extends Instruction(() => acc += parameter)
  11.   case class Jmp(parameter:Int) extends Instruction(() => pc += parameter - 1){override def switch() = f = () => ()}
  12.   case class Nop(parameter:Int) extends Instruction(() => ()){override def switch() = f = () => pc += parameter - 1}
  13.  
  14.   val PATTERN = """(\w{3}) ((?:[+]|[-])\d+)""".r
  15.   val instructions = Source.fromFile("day8").getLines().map{
  16.     case PATTERN(op,parameter) =>
  17.       op match {
  18.       case "acc" => new Acc(parameter.toInt) case "jmp" => new Jmp(parameter.toInt) case "nop" => new Nop(parameter.toInt)
  19.     }
  20.   }.toList
  21.   var pc = 0; var acc = 0;
  22.  
  23.   def run(reset:Boolean = true):Boolean = {
  24.     if(reset){ instructions.foreach(x => x.timesRun = 0); acc = 0; pc = 0 }
  25.     instructions(pc).run()
  26.     if(pc >= instructions.length) true else if (instructions(pc).timesRun < 1) run(false) else false
  27.   }
  28.   run()
  29.   println("part 1: " + acc)
  30.   println("part 2: " + instructions.indices.map{ x => instructions(x).switch(); val result = (run(),acc); instructions(x).restore(); result}.filter(x => x._1).head._2)
  31. }
Advertisement
Add Comment
Please, Sign In to add comment