Compare commits

..
2 Commits
Author SHA1 Message Date
jeremy a70d9fafee Day 2: Sum calculation in program 2023-12-03 00:41:30 +01:00
jeremy 64b020ff65 Day 2: Unit test 2023-12-03 00:34:22 +01:00
2 changed files with 22 additions and 4 deletions

No files matched your search

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