Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created January 27, 2023 11:49
Show Gist options
  • Save waynejo/7234d84bf0e5e966a0ea977a7b5062e9 to your computer and use it in GitHub Desktop.
Save waynejo/7234d84bf0e5e966a0ea977a7b5062e9 to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.annotation.tailrec
import scala.io.StdIn
enum Shape:
case rock, paper, scissors
def winner: Shape =
this match {
case Shape.rock => Shape.paper
case Shape.paper => Shape.scissors
case Shape.scissors => Shape.rock
}
def shapeFromAbc(text: String): Shape =
text match {
case "A" => Shape.rock
case "B" => Shape.paper
case "C" => Shape.scissors
}
def shapeFromXyz(text: String): Shape =
text match {
case "X" => Shape.rock
case "Y" => Shape.paper
case "Z" => Shape.scissors
}
def outcomeScore(opposite: Shape, you: Shape): Int =
if opposite.winner == you then
6
else if opposite == you then
3
else
0
def shapeScore(you: Shape): Int =
you match {
case Shape.rock => 1
case Shape.paper => 2
case Shape.scissors => 3
}
def myOutcome(opposite: Shape, text: String): Shape =
text match {
case "X" => opposite.winner.winner
case "Y" => opposite
case "Z" => opposite.winner
}
def solve2_1(values: Vector[String]): Int =
values.map(line => {
val Array(v0, v1) = line.split(" ")
val opposite = shapeFromAbc(v0)
val you = shapeFromXyz(v1)
outcomeScore(opposite, you) + shapeScore(you)
}).sum
def solve2_2(values: Vector[String]): Int =
values.map(line => {
val Array(v0, v1) = line.split(" ")
val opposite = shapeFromAbc(v0)
val you = myOutcome(opposite, v1)
outcomeScore(opposite, you) + shapeScore(you)
}).sum
@main def solve2(): Unit =
val in = new FileInputStream("example2-2.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine())
.takeWhile(line => null != line)
.toVector
println(solve2_1(inputs))
println(solve2_2(inputs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment