Day 2: Compute power of minimum set of cubes

This commit is contained in:
jeremy committed 2023-12-03 01:11:46 +01:00
1 parent 11d0318153
commit 973b2febb0
3 files changed
+27 -11

No files matched your search

+4 -2
View File
@@ -3,6 +3,8 @@ import day2.Day2
import day2.Hand import day2.Hand
fun main() { fun main() {
println("Day 1: ${Day1.answerOne()} && ${Day1.answerTwo()}") println("Day 1-1: ${Day1.answerOne()}")
println("Day 2: ${Day2.sumOfCompatibleGames("src/main/resources/day2/input.txt", Hand(12,13,14))}") println("Day 1-2: ${Day1.answerTwo()}")
println("Day 2-1: ${Day2.sumOfCompatibleGames("src/main/resources/day2/input.txt", Hand(12,13,14))}")
println("Day 2-2: ${Day2.powerOfMinimumSetOfCubes("src/main/resources/day2/input.txt")}")
} }
+17 -8
View File
@@ -9,6 +9,10 @@ object Day2 {
.map(Game::id) .map(Game::id)
.sum() .sum()
fun powerOfMinimumSetOfCubes(file: String) = readGames(file)
.map(Game::powerOfHands)
.sum()
private fun readGames(file: String): List<Game> = private fun readGames(file: String): List<Game> =
File(file) File(file)
.readLines() .readLines()
@@ -17,15 +21,20 @@ object Day2 {
} }
data class Game(val id: Int, val hands: List<Hand>) { data class Game(val id: Int, val hands: List<Hand>) {
fun isCompatibleWith(hand: Hand) = fun isCompatibleWith(hand: Hand) =
hand.fitsIn( hand.fitsIn(maxOfHands())
hands.fold(Hand(0, 0, 0)) { currentMax: Hand, next: Hand ->
Hand( fun powerOfHands() = maxOfHands().let { it.red * it.green * it.blue }
maxOf(currentMax.red, next.red),
maxOf(currentMax.green, next.green), private fun maxOfHands() = hands.fold(Hand(0, 0, 0)) { currentMax: Hand, next: Hand ->
maxOf(currentMax.blue, next.blue) Hand(
) maxOf(currentMax.red, next.red),
}) maxOf(currentMax.green, next.green),
maxOf(currentMax.blue, next.blue)
)
}
companion object { companion object {
+6 -1
View File
@@ -5,7 +5,12 @@ import org.junit.jupiter.api.Test
class Day2Test { class Day2Test {
@Test @Test
fun readGames() { fun sumOfCompatibleGames() {
assert(Day2.sumOfCompatibleGames("src/test/resources/day2/input.txt", Hand(12, 13, 14)) == 8) assert(Day2.sumOfCompatibleGames("src/test/resources/day2/input.txt", Hand(12, 13, 14)) == 8)
} }
@Test
fun powerOfMinimumSetOfCubes() {
assert(Day2.powerOfMinimumSetOfCubes("src/test/resources/day2/input.txt") == 2286)
}
} }