@@ -13,13 +13,8 @@ import inputs.Input.loadFileSync
1313def loadInput (): String = loadFileSync(s " $currentDir/../input/day02 " )
1414
1515case class Colors (color : String , count : Int )
16- case class Game (game : Int , hands : List [List [Colors ]])
17- type Config = Map [String , Int ]
18-
19- def validate (config : Config , game : Game ): Boolean =
20- game.hands.forall:
21- _.forall:
22- case Colors (color, count) => config.getOrElse(color, 0 ) >= count
16+ case class Game (id : Int , hands : List [List [Colors ]])
17+ type Summary = Game => Int
2318
2419def parseColors (pair : String ): Colors =
2520 val Array (count0, color0) = pair.split(" " )
@@ -30,26 +25,38 @@ def parse(line: String): Game =
3025 val Array (_, id) = game0.split(" " ): @ unchecked
3126 val hands0 = hands.split(" ; " ).toList
3227 val hands1 = hands0.map(_.split(" , " ).map(parseColors).toList)
33- Game (game = id.toInt, hands = hands1)
34-
35- def part1 (input : String ): Int =
36- val clauses = input.linesIterator.map(parse).toList
37- val config = Map (
38- " red" -> 12 ,
39- " green" -> 13 ,
40- " blue" -> 14 ,
41- )
42- clauses.collect({ case game if validate(config, game) => game.game }).sum
43-
44- def part2 (input : String ): Int =
45- val clauses = input.linesIterator.map(parse).toList
46- val initial = Seq (" red" , " green" , " blue" ).map(_ -> 0 ).toMap
47-
48- def minCubes (game : Game ): Int =
49- val maximums = game.hands.foldLeft(initial): (maximums, colors) =>
50- colors.foldLeft(maximums):
51- case (maximums, Colors (color, count)) =>
52- maximums + (color -> (maximums(color) `max` count))
53- maximums.values.product
54-
55- clauses.map(minCubes).sum
28+ Game (id = id.toInt, hands = hands1)
29+
30+ def solution (input : String , summarise : Summary ): Int =
31+ input.linesIterator.map(parse andThen summarise).sum
32+
33+ val possibleCubes = Map (
34+ " red" -> 12 ,
35+ " green" -> 13 ,
36+ " blue" -> 14 ,
37+ )
38+
39+ def validGame (game : Game ): Boolean =
40+ game.hands.forall: hand =>
41+ hand.forall:
42+ case Colors (color, count) =>
43+ count <= possibleCubes.getOrElse(color, 0 )
44+
45+ val possibleGame : Summary =
46+ case game if validGame(game) => game.id
47+ case _ => 0
48+
49+ def part1 (input : String ): Int = solution(input, possibleGame)
50+
51+ val initial = Seq (" red" , " green" , " blue" ).map(_ -> 0 ).toMap
52+
53+ def minimumCubes (game : Game ): Int =
54+ var maximums = initial
55+ for
56+ hand <- game.hands
57+ Colors (color, count) <- hand
58+ do
59+ maximums += (color -> (maximums(color) `max` count))
60+ maximums.values.product
61+
62+ def part2 (input : String ): Int = solution(input, minimumCubes)
0 commit comments