52 lines
1.4 KiB
Scala
52 lines
1.4 KiB
Scala
package aoc.y2017
|
|
|
|
import aoc.Day
|
|
|
|
object Day05 extends Day {
|
|
|
|
trait Stepper {
|
|
def step(p: Program): Program
|
|
}
|
|
|
|
case class Program(instructions: List[Int], index: Int = 0) {
|
|
|
|
def step(implicit stepper: Stepper): Program = stepper.step(this)
|
|
|
|
}
|
|
|
|
def countSteps(p: Program, steps: Int = 0)(implicit stepper: Stepper): Int = {
|
|
print(s"\rCurrent Instruction: ${p.index}/${p.instructions.size}${" " * p.instructions.size.toString.length}")
|
|
if (p.index >= p.instructions.size) {
|
|
steps
|
|
} else {
|
|
countSteps(p.step, steps + 1)
|
|
}
|
|
}
|
|
|
|
def getStartingProgram(input: String): Program = {
|
|
val lines = input.lines.map(_.toInt)
|
|
Program(lines.toList)
|
|
}
|
|
|
|
override def part1(input: String): String = {
|
|
implicit val stepper: Stepper = (p: Program) => {
|
|
val instruction = p.instructions(p.index)
|
|
val newList = p.instructions.updated(p.index, instruction + 1)
|
|
Program(newList, p.index + instruction)
|
|
}
|
|
println()
|
|
countSteps(getStartingProgram(input)).toString
|
|
}
|
|
|
|
override def part2(input: String): String = {
|
|
implicit val stepper: Stepper = (p: Program) => {
|
|
val instruction = p.instructions(p.index)
|
|
val newList = p.instructions.updated(p.index, if (instruction >= 3) instruction - 1 else instruction + 1)
|
|
Program(newList, p.index + instruction)
|
|
}
|
|
println()
|
|
countSteps(getStartingProgram(input)).toString
|
|
}
|
|
|
|
}
|