From 0528d4b50ecb22920a56f05631d7c482e46e196d Mon Sep 17 00:00:00 2001 From: Luke Hubmayer-Werner Date: Fri, 2 Dec 2022 19:20:24 +1030 Subject: [PATCH] more scala --- 2022/day2-v2.scala | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 2022/day2-v2.scala diff --git a/2022/day2-v2.scala b/2022/day2-v2.scala new file mode 100644 index 0000000..43a6f1d --- /dev/null +++ b/2022/day2-v2.scala @@ -0,0 +1,39 @@ +import scala.io.Source +import scala.math.floorMod + +enum RPS(val score: Int): + case Rock extends RPS(1) + case Paper extends RPS(2) + case Scissors extends RPS(3) + + def +(amount: Int) = RPS.fromOrdinal(floorMod(ordinal + amount, 3)) + def -(amount: Int) = RPS.fromOrdinal(floorMod(ordinal - amount, 3)) + def -(other: RPS) = score - other.score + + def vs(other: RPS) = floorMod(this - other, 3) match + case 1 => 6 + case 2 => 0 + case _ => 3 + +val moveMap = Map("A"->RPS.Rock, "B"->RPS.Paper, "C"->RPS.Scissors, "X"->RPS.Rock, "Y"->RPS.Paper, "Z"->RPS.Scissors) + +@main def main() = + val strategyGuide = Source.fromFile("day2-input").getLines.map(_.split(" ")).toArray // Can't leave it lazy as Part 1 will consume it + // val strategyGuide = Source.fromString("A Y\nB X\nC Z\n").getLines.map(_.split(" ")).toArray + + // Part 1 - evaluate all moves in the guide using moveMap and tally score + println(strategyGuide.map(movePair=> + val theirMove = moveMap(movePair(0)) + val ourMove = moveMap(movePair(1)) + ourMove.score + (ourMove vs theirMove) + ).sum) + + // Part 2 - X->lose, Y->draw, Z->win + println(strategyGuide.map(movePair=> + val theirMove = moveMap(movePair(0)) + val ourMove = movePair(1) match + case "X" => theirMove - 1 + case "Y" => theirMove + case "Z" => theirMove + 1 + ourMove.score + (ourMove vs theirMove) + ).sum) \ No newline at end of file