Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created March 10, 2023 12:38
Show Gist options
  • Save waynejo/897ca3aa58ebf1daec37e38a6a1fd523 to your computer and use it in GitHub Desktop.
Save waynejo/897ca3aa58ebf1daec37e38a6a1fd523 to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.annotation.{tailrec, targetName}
import scala.io.StdIn
import scala.math.abs
sealed trait Command {
def cycle: Int
}
case object Noop extends Command {
def cycle = 1
}
case class AddX(x: Int) extends Command {
def cycle = 2
}
case class Cpu(register: Int, command: Command, cycle: Int)
def simulate(acc: Vector[Cpu], commands: Vector[Command]): Vector[Cpu] =
acc.last match
case cpu@Cpu(_, _, cycle) if 1 < cycle =>
simulate(acc :+ cpu.copy(cycle = cycle - 1), commands)
case cpu@Cpu(register, cpuCommand, _) =>
val nextCpu = cpuCommand match {
case Noop =>
cpu
case AddX(x) =>
cpu.copy(register = register + x)
}
commands.headOption match
case Some(command) =>
simulate(acc :+ nextCpu.copy(command = command, cycle = command.cycle), commands.tail)
case _ =>
acc
def solve10_1(commands: Vector[Command]): Int =
val cpu = Cpu(1, commands.head, commands.head.cycle)
val result = simulate(Vector(cpu), commands.tail)
Vector(20, 60, 100, 140, 180, 220).map(idx => result(idx - 1).register * idx).sum
def solve10_2(commands: Vector[Command]): String =
val cpu = Cpu(1, commands.head, commands.head.cycle)
val result = simulate(Vector(cpu), commands.tail)
val printed = (0 until 240).flatMap { idx =>
val width: Int = 40
val centerX = result(idx).register
val c: String = if 1 >= abs(centerX - (idx % width)) then "#" else "."
if idx % width == width - 1 then
c + "\n"
else
c
}
printed.mkString
@main def solve10(): Unit =
val in = new FileInputStream("example10-2.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine())
.takeWhile(line => null != line)
.map(_.split(" ") match
case Array("addx", v) => AddX(v.toInt)
case _ => Noop
)
.toVector
println(solve10_1(inputs))
println(solve10_2(inputs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment