From 69461192cacc2c822d5daa732232bf43d350dc8d Mon Sep 17 00:00:00 2001 From: Luke Hubmayer-Werner Date: Mon, 5 Dec 2022 19:57:11 +1030 Subject: [PATCH] 2022 Day 5 Scala --- 2022/day5.scala | 59 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 2022/day5.scala diff --git a/2022/day5.scala b/2022/day5.scala new file mode 100644 index 0000000..e165587 --- /dev/null +++ b/2022/day5.scala @@ -0,0 +1,59 @@ +import java.nio.file.Files +import java.nio.file.Paths +import scala.collection.mutable.ArrayDeque + +type Stack[A] = ArrayDeque[A] +val Stack = ArrayDeque + +val numberPattern = raw"((?:(? aos.reverse.map(_.substring(i,i+1)).reduceLeft(_+_)) + else (i => aos.map(_.substring(i,i+1)).reduceLeft(_+_)) + if reverseX then + (0 until aos(0).length).reverse.map(mapping) + else + (0 until aos(0).length).map(mapping) + +def getStacksString(stacks: Map[Int, Stack[Char]]): String = stacks.keys.toBuffer.sorted.map(stacks(_).last.toString).reduceLeft(_+_) + +@main def main() = + val (input_stacks, input_orders) = Files.readString(Paths.get("input/5")).partition2() + val stacks_s = input_stacks + .transpose(reverseY = true) + .map(_.replaceAll(raw"[\[\]]", " ").strip) + .filter(_.length > 0) + .map(s => (s.substring(0,1).toInt, s.substring(1))).toMap + val orders = input_orders.map(numberPattern.findAllIn(_).map(_.toInt).toArray).toArray // Can't leave lazy or Part 1 will consume it all + + var stacks: Map[Int, Stack[Char]] = stacks_s.map((k,v) => (k, v.toCharArray.to(Stack))).toMap + for order <- orders do + val (amount, i_source, i_dest) = (order(0), order(1), order(2)) + val source = stacks(i_source) + val dest = stacks(i_dest) + // println(s"Moving $amount from ${source.mkString} to ${dest.mkString}") + // print(s"Doing amount $amount : ") + for _ <- 1 to amount do + dest.append(source.removeLast()) + // print(". ") + // print("\n") + // println(s"Moved $amount from ${source.mkString} to ${dest.mkString}") + println(s"Part 1: ${getStacksString(stacks)}") + + stacks = stacks_s.map((k,v) => (k, v.toCharArray.to(Stack))).toMap + for order <- orders do + val (amount, i_source, i_dest) = (order(0), order(1), order(2)) + val source = stacks(i_source) + val dest = stacks(i_dest) + dest.appendAll(source.takeRight(amount)) + source.dropRightInPlace(amount) + println(s"Part 2: ${getStacksString(stacks)}")