Day 2
This commit is contained in:
parent
069a9e35f6
commit
44da9ddd56
2 changed files with 158 additions and 0 deletions
58
src/day02.scala
Normal file
58
src/day02.scala
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package aoc
|
||||
package day02
|
||||
|
||||
val dayNumber = "02"
|
||||
|
||||
@main def part1: Unit =
|
||||
println(part1(loadInput(dayNumber)))
|
||||
|
||||
@main def part2: Unit =
|
||||
println(part2(loadInput(dayNumber)))
|
||||
|
||||
def part1(input: String): String =
|
||||
val bagContent = Map(
|
||||
"red" -> 12,
|
||||
"green" -> 13,
|
||||
"blue" -> 14
|
||||
)
|
||||
|
||||
input
|
||||
.split("\n")
|
||||
.map(line =>
|
||||
(
|
||||
line match
|
||||
case s"Game $number:$rest" => number.toInt
|
||||
,
|
||||
"""(\d+ \w+)""".r
|
||||
.findAllIn(line)
|
||||
.toList
|
||||
.map { case s"$count $color" =>
|
||||
(count.toInt, color)
|
||||
}
|
||||
)
|
||||
)
|
||||
.collect {
|
||||
case (gameNumber, sets)
|
||||
if sets.forall((count, color) => bagContent(color) >= count) =>
|
||||
gameNumber
|
||||
}
|
||||
.sum
|
||||
.toString
|
||||
|
||||
def part2(input: String): String =
|
||||
input
|
||||
.split("\n")
|
||||
.map(line =>
|
||||
"""(\d+ \w+)""".r
|
||||
.findAllIn(line)
|
||||
.toList
|
||||
.map { case s"$count $color" =>
|
||||
(count.toInt, color)
|
||||
}
|
||||
)
|
||||
.map(_.foldLeft(Map().withDefaultValue(0)) { case (acc, (count, color)) =>
|
||||
acc.updated(color, Math.max(acc(color), count))
|
||||
})
|
||||
.map(_.values.product)
|
||||
.sum
|
||||
.toString
|
||||
Loading…
Add table
Add a link
Reference in a new issue