Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.io.Source
- object Day8 extends App {
- abstract class Instruction(var f:(() => Unit), var timesRun:Int = 0){
- val originalF = f
- def run() = {pc += 1;f(); timesRun += 1}
- def switch() = ()
- def restore() = f = originalF
- }
- case class Acc(parameter:Int) extends Instruction(() => acc += parameter)
- case class Jmp(parameter:Int) extends Instruction(() => pc += parameter - 1){override def switch() = f = () => ()}
- case class Nop(parameter:Int) extends Instruction(() => ()){override def switch() = f = () => pc += parameter - 1}
- val PATTERN = """(\w{3}) ((?:[+]|[-])\d+)""".r
- val instructions = Source.fromFile("day8").getLines().map{
- case PATTERN(op,parameter) =>
- op match {
- case "acc" => new Acc(parameter.toInt) case "jmp" => new Jmp(parameter.toInt) case "nop" => new Nop(parameter.toInt)
- }
- }.toList
- var pc = 0; var acc = 0;
- def run(reset:Boolean = true):Boolean = {
- if(reset){ instructions.foreach(x => x.timesRun = 0); acc = 0; pc = 0 }
- instructions(pc).run()
- if(pc >= instructions.length) true else if (instructions(pc).timesRun < 1) run(false) else false
- }
- run()
- println("part 1: " + acc)
- println("part 2: " + instructions.indices.map{ x => instructions(x).switch(); val result = (run(),acc); instructions(x).restore(); result}.filter(x => x._1).head._2)
- }
Advertisement
Add Comment
Please, Sign In to add comment