2 Commits

2 changed files with 22 additions and 4 deletions
Split View
  1. +21
    -3
      src/main/kotlin/day2/Day2.kt
  2. +1
    -1
      src/test/kotlin/day2/Day2Test.kt

+ 21
- 3
src/main/kotlin/day2/Day2.kt View File

@ -4,13 +4,29 @@ import java.io.File
object Day2 {
fun readGames(file: File = File("src/main/resources/day2/input.txt")): List<Game> = file
.readLines()
.map(Game.Companion::parse)
fun sumOfCompatibleGames(hand: Hand) = readGames()
.filter { it.isCompatibleWith(hand) }
.map(Game::id)
.sum()
private fun readGames(): List<Game> =
File("src/main/resources/day2/input.txt")
.readLines()
.map(Game.Companion::parse)
}
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)
)
})
companion object {
/**
@ -30,6 +46,8 @@ data class Game(val id: Int, val hands: List) {
}
data class Hand(val red: Int, val green: Int, val blue: Int) {
fun fitsIn(other: Hand) = red >= other.red && green >= other.green && blue >= other.blue
companion object {
/**

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

@ -6,6 +6,6 @@ class Day2Test {
@Test
fun readGames() {
Day2.readGames()
assert(Day2.sumOfCompatibleGames(Hand(12, 13, 14)) == 8)
}
}

Loading…
Cancel
Save