aoc2023/Day2.scala

46 lines
1.1 KiB
Scala
Raw Permalink 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-03 16:15:52 +00:00
num.into: num =>
"red" ^^^ ((h: Hand) => h.copy(red = num)) |
"green" ^^^ ((h: Hand) => h.copy(green = num)) |
"blue" ^^^ ((h: Hand) => h.copy(blue = num))
2023-12-02 14:31:39 +00:00
val hand = rep1sep(update, ",").map(_.foldRight(Hand(0, 0, 0))(_(_)))
2023-12-09 12:23:52 +00:00
val game = "Game" ~ num ~ ":" ~ repsep(hand, ";") ^^ { case (_ ~ num ~ _ ~ hands) =>
Game(num, hands)
2023-12-02 14:31:39 +00:00
}
end Parser
// Part 1
def getGames = lines.map(Parser.parse(Parser.game, _).get)
def part1 =
val games = getGames.toList
val res =
games
2023-12-09 12:23:52 +00:00
.filter(g => g.hands.forall(h => h.red <= 12 && h.green <= 13 && h.blue <= 14))
2023-12-02 14:31:39 +00:00
.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