aoc2023/Day2.scala

49 lines
1.2 KiB
Scala
Raw Normal View History

2023-12-03 15:50:17 +00:00
package aoc.day2
2023-12-02 14:31:39 +00:00
import aoc._
case class Hand(red: Int, green: Int, blue: Int):
def max(other: Hand) =
Hand(red max other.red, green max other.green, blue max other.blue)
def power = red * green * blue
case class Game(id: Int, hands: List[Hand]):
def power =
hands.foldLeft(Hand(0, 0, 0))(_ max _).power
2023-12-03 15:50:17 +00:00
object Parser extends CommonParser:
2023-12-02 14:31:39 +00:00
val update =
2023-12-02 14:39:06 +00:00
num ~ (
"red" ^^ (_ => (num: Int) => (h: Hand) => h.copy(red = num)) |
"green" ^^ (_ => (num: Int) => (h: Hand) => h.copy(green = num)) |
"blue" ^^ (_ => (num: Int) => (h: Hand) => h.copy(blue = num))
) ^^ { case (num ~ f) => f(num) }
2023-12-02 14:31:39 +00:00
val hand = rep1sep(update, ",").map(_.foldRight(Hand(0, 0, 0))(_(_)))
val game = "Game" ~ num ~ ":" ~ repsep(hand, ";") ^^ {
case (_ ~ num ~ _ ~ hands) => Game(num, hands)
}
end Parser
// Part 1
def getGames = lines.map(Parser.parse(Parser.game, _).get)
def part1 =
val games = getGames.toList
val res =
games
.filter(g =>
g.hands.forall(h => h.red <= 12 && h.green <= 13 && h.blue <= 14)
)
.map(_.id)
.sum
println(res)
def part2 =
val res = getGames.map(_.power).sum
println(res)
@main def Day2(part: Int) = part match
case 1 => part1
case 2 => part2