Skip to content

Instantly share code, notes, and snippets.

@waynejo
Last active February 17, 2023 13:24
Show Gist options
  • Save waynejo/7100fc3c7667c07c1f73aa22c39a2abe to your computer and use it in GitHub Desktop.
Save waynejo/7100fc3c7667c07c1f73aa22c39a2abe to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.annotation.tailrec
import scala.io.StdIn
case class Command(from: Int, to: Int, value: Int)
@tailrec
def _step(crate: Vector[Vector[Char]], commands: Vector[Command], shouldReverse: Boolean): Vector[Vector[Char]] =
commands.headOption match
case None => crate
case Some(command) =>
val newCrate = crate.zipWithIndex.map { (c, i) =>
if i == command.from then
c.drop(command.value)
else if i == command.to then
if shouldReverse then
crate(command.from).take(command.value).reverse ++ c
else
crate(command.from).take(command.value) ++ c
else
c
}
_step(newCrate, commands.tail, shouldReverse)
def solve5_1(crate: Vector[Vector[Char]], commands: Vector[Command]): String =
_step(crate, commands, true).map(_.head).mkString("")
def solve5_2(crate: Vector[Vector[Char]], commands: Vector[Command]): String =
_step(crate, commands, false).map(_.head).mkString("")
@main def solve5(): Unit =
val in = new FileInputStream("example5-2.in")
System.setIn(in)
val crate = Iterator.continually(StdIn.readLine())
.takeWhile(line => line.strip().nonEmpty)
.map(_.toVector)
.toVector
.transpose
.zipWithIndex
.filter(_._2 % 4 == 1)
.map(_._1.init.filter(x => x != ' '))
val commands = Iterator.continually(StdIn.readLine())
.takeWhile(line => null != line)
.map(line => {
val parts = line.split(" ")
Command(parts(3).toInt - 1, parts(5).toInt - 1, parts(1).toInt)
})
.toVector
println(solve5_1(crate, commands))
println(solve5_2(crate, commands))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment