-
Notifications
You must be signed in to change notification settings - Fork 3
/
Day05.scala
32 lines (26 loc) · 1.07 KB
/
Day05.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package AdventOfCode2022
object Day05:
def stacks(input: Seq[String]): Seq[String] = input
.take(input.indexOf("") - 1)
.map(line => (1 to line.length by 4).map(line))
.transpose
.map(_.mkString.trim)
def moves(input: Seq[String]): Seq[(Int, Int, Int)] = input
.drop(input.indexOf("") + 1)
.map { line =>
val Array(amount, from, to) = line.split("\\D+").tail.map(_.toInt)
(amount, from - 1, to - 1)
}
def play(input: Seq[String], reverse: Boolean): String =
moves(input).foldLeft(stacks(input)) { case (state, (amount, from, to)) =>
val (prefix, suffix) = state(from).splitAt(amount)
val result = if (reverse) prefix.reverse else prefix
state.updated(from, suffix).updated(to, result + state(to))
}
.map(_.head).mkString
def part1(input: Seq[String]): String = play(input, true)
def part2(input: Seq[String]): String = play(input, false)
def main(args: Array[String]): Unit =
val data = io.Source.fromResource("AdventOfCode2022/Day05.txt").getLines().toSeq
println(part1(data))
println(part2(data))