Skip to content

Instantly share code, notes, and snippets.

@tong92
Created February 17, 2023 13:50
Show Gist options
  • Save tong92/b54b311312024c3273c621907581a861 to your computer and use it in GitHub Desktop.
Save tong92/b54b311312024c3273c621907581a861 to your computer and use it in GitHub Desktop.
import scala.io.Source
def input2Stack(input: List[String]): List[String] =
input.transpose.filter(xs => xs.head != ' ').map(_.mkString.trim())
def sperateInput(input: List[String], res: List[String]): (List[String], List[String]) =
val (x :: xs) = input
if x == "" then return (res, xs)
sperateInput(xs, x :: res)
def runCommands(commands: List[String], origin: List[String], cnt: Int, fn: (String, List[String]) => List[String]): List[String] =
if commands.length == cnt then return origin
runCommands(commands, fn(commands(cnt), origin), cnt + 1, fn)
val commandReg = raw"move (\d+) from (\d+) to (\d+)".r
def runCommand(input: String, origin: List[String]): List[String] =
def inner(from: Int, to: Int, cnt: Int): List[String] =
val fromTxt = origin(from).dropRight(cnt)
val toTxt = origin(to) + origin(from).takeRight(cnt).reverse
origin.updated(from, fromTxt).updated(to, toTxt)
input match
case commandReg(cnt, from, to) => inner(from.toInt - 1, to.toInt - 1, cnt.toInt)
def runCommand2(input: String, origin: List[String]): List[String] =
def inner(from: Int, to: Int, cnt: Int): List[String] =
val fromTxt = origin(from).dropRight(cnt)
val toTxt = origin(to) + origin(from).takeRight(cnt)
origin.updated(from, fromTxt).updated(to, toTxt)
input match
case commandReg(cnt, from, to) => inner(from.toInt - 1, to.toInt - 1, cnt.toInt)
def ans1(xs: List[String]): String =
val (firstInput, secondInput) = sperateInput(xs, Nil)
val stacks = input2Stack(firstInput)
val result = runCommands(secondInput, stacks, 0, runCommand)
result.map(_.takeRight(1)).mkString
def ans2(xs: List[String]): String =
val (firstInput, secondInput) = sperateInput(xs, Nil)
val stacks = input2Stack(firstInput)
val result = runCommands(secondInput, stacks, 0, runCommand2)
result.map(_.takeRight(1)).mkString
def solve =
val input = Source.fromFile("day5.txt").getLines.toList
println(ans1(input))
println(ans2(input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment