Browse Source

Day 2: Compute power of minimum set of cubes

master
Jeremy Soumokil 2 years ago
parent
commit
973b2febb0
3 changed files with 27 additions and 11 deletions
  1. +4
    -2
      src/main/kotlin/Main.kt
  2. +17
    -8
      src/main/kotlin/day2/Day2.kt
  3. +6
    -1
      src/test/kotlin/day2/Day2Test.kt

+ 4
- 2
src/main/kotlin/Main.kt View File

@ -3,6 +3,8 @@ import day2.Day2
import day2.Hand
fun main() {
println("Day 1: ${Day1.answerOne()} && ${Day1.answerTwo()}")
println("Day 2: ${Day2.sumOfCompatibleGames("src/main/resources/day2/input.txt", Hand(12,13,14))}")
println("Day 1-1: ${Day1.answerOne()}")
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
src/main/kotlin/day2/Day2.kt View File

@ -9,6 +9,10 @@ object Day2 {
.map(Game::id)
.sum()
fun powerOfMinimumSetOfCubes(file: String) = readGames(file)
.map(Game::powerOfHands)
.sum()
private fun readGames(file: String): List<Game> =
File(file)
.readLines()
@ -17,15 +21,20 @@ object Day2 {
}
data class Game(val id: Int, val hands: List<Hand>) {
fun isCompatibleWith(hand: Hand) =
hand.fitsIn(
hands.fold(Hand(0, 0, 0)) { currentMax: Hand, next: Hand ->
Hand(
maxOf(currentMax.red, next.red),
maxOf(currentMax.green, next.green),
maxOf(currentMax.blue, next.blue)
)
})
hand.fitsIn(maxOfHands())
fun powerOfHands() = maxOfHands().let { it.red * it.green * it.blue }
private fun maxOfHands() = hands.fold(Hand(0, 0, 0)) { currentMax: Hand, next: Hand ->
Hand(
maxOf(currentMax.red, next.red),
maxOf(currentMax.green, next.green),
maxOf(currentMax.blue, next.blue)
)
}
companion object {

+ 6
- 1
src/test/kotlin/day2/Day2Test.kt View File

@ -5,7 +5,12 @@ import org.junit.jupiter.api.Test
class Day2Test {
@Test
fun readGames() {
fun sumOfCompatibleGames() {
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)
}
}

Loading…
Cancel
Save