Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created January 22, 2021 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waynejo/5cb541e171d1ff79bc14dad001944afe to your computer and use it in GitHub Desktop.
Save waynejo/5cb541e171d1ff79bc14dad001944afe to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.io.StdIn
@main def solve8() =
case class Instruction(code: String, value: Int)
def solve(instructions: Vector[Instruction], hitCount: Array[Int], pc: Int = 0, acc: Int = 0): Int = {
if 1 <= hitCount(pc) then
acc
else
hitCount(pc) += 1
val instruction = instructions(pc)
instruction.code match {
case "acc" =>
solve(instructions, hitCount, pc + 1, acc + instruction.value)
case "jmp" =>
solve(instructions, hitCount, pc + instruction.value, acc)
case _ =>
solve(instructions, hitCount, pc + 1, acc)
}
}
val in = new FileInputStream("example8-1.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine()).takeWhile(_ != null).toVector
val instructions = inputs.map { line =>
val Array(code, value) = line.trim.split(" ")
Instruction(code, value.toInt)
}
println(solve(instructions, Array.ofDim(instructions.size)))
import java.io.FileInputStream
import scala.io.StdIn
@main def solve8() =
case class Instruction(code: String, value: Int)
def run(instructions: Vector[Instruction], hitCount: Array[Int], lastPc: Int = 0, pc: Int = 0, acc: Int = 0): Option[Int] = {
if instructions.size <= pc then {
Some(acc)
} else if 1 <= hitCount(pc) then {
None
} else
hitCount(pc) += 1
val instruction = instructions(pc)
instruction.code match {
case "acc" =>
run(instructions, hitCount, pc, pc + 1, acc + instruction.value)
case "jmp" =>
run(instructions, hitCount, pc, pc + instruction.value, acc)
case _ =>
run(instructions, hitCount, pc, pc + 1, acc)
}
}
def solve(instructions: Vector[Instruction]): Int = {
instructions.indices.toIterable.map { idx =>
if instructions(idx).code == "jmp" then {
val patchedInstructions = instructions.updated(idx, instructions(idx).copy(code = "nop"))
run(patchedInstructions, Array.ofDim(instructions.size))
} else {
Option.empty[Int]
}
}.find(_.nonEmpty).flatten.getOrElse(0)
}
val in = new FileInputStream("example8-1.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine()).takeWhile(_ != null).toVector
val instructions = inputs.map { line =>
val Array(code, value) = line.trim.split(" ")
Instruction(code, value.toInt)
}
println(solve(instructions))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment