This commit is contained in:
Paul-Henri Froidmont 2022-12-05 07:00:43 +01:00
parent 7028e6edf0
commit b9465481a1
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 563 additions and 0 deletions

49
aoc/src/Day5.scala Normal file
View file

@ -0,0 +1,49 @@
import scala.io.Source
import scala.collection.mutable.Stack
object Day5 extends App:
val input = Source
.fromURL(getClass.getResource("day5Input.txt"))
.mkString
.split('\n')
.toList
val crates = input
.takeWhile(_ != "")
.dropRight(1)
.map(_.grouped(4).toList)
.transpose
.map(_.flatMap(_.find(_.isLetter)))
.toArray
val moves = input
.dropWhile(_ != "")
.tail
.map(_.split(" ").flatMap(_.toIntOption))
.map { case Array(count, from, to) => (count, from - 1, to - 1) }
val part1 = moves
.foldLeft(crates) { case (crates, (count, from, to)) =>
val movedCrates = crates(from).take(count)
crates
.updated(from, crates(from).drop(count))
.updated(to, crates(to).prependedAll(movedCrates.reverse))
}.toList
.map(_.head)
.mkString
println(s"Part 1: $part1")
val part2 = moves
.foldLeft(crates) { case (crates, (count, from, to)) =>
val movedCrates = crates(from).take(count)
crates
.updated(from, crates(from).drop(count))
.updated(to, crates(to).prependedAll(movedCrates))
}.toList
.map(_.head)
.mkString
println(s"Part 2: $part2")
end Day5