|
| 1 | +package de.ronny_h.aoc.year2015.day14 |
| 2 | + |
| 3 | +import de.ronny_h.aoc.AdventOfCode |
| 4 | +import kotlin.math.min |
| 5 | + |
| 6 | +fun main() = ReindeerOlympics().run(2660, 1256) |
| 7 | + |
| 8 | +class ReindeerOlympics : AdventOfCode<Int>(2015, 14) { |
| 9 | + override fun part1(input: List<String>): Int = input.parse().maxReindeerDistanceIn(2503) |
| 10 | + override fun part2(input: List<String>): Int = input.parse().pointsOfWinnerIn(2503) |
| 11 | +} |
| 12 | + |
| 13 | +fun List<Reindeer>.maxReindeerDistanceIn(secondsTotal: Int) = map { it.reindeerDistanceIn(secondsTotal) }.max() |
| 14 | + |
| 15 | +fun List<Reindeer>.pointsOfWinnerIn(secondsTotal: Int): Int { |
| 16 | + val reindeerPoints = MutableList(size) { 0 } |
| 17 | + for (seconds in 1..secondsTotal) { |
| 18 | + val distances = map { it.reindeerDistanceIn(seconds) }.withIndex() |
| 19 | + val leaderDistance = distances.maxOf { it.value } |
| 20 | + val leaders = distances.filter { it.value == leaderDistance } |
| 21 | + leaders.forEach { |
| 22 | + reindeerPoints[it.index]++ |
| 23 | + } |
| 24 | + } |
| 25 | + return reindeerPoints.max() |
| 26 | +} |
| 27 | + |
| 28 | +private fun Reindeer.reindeerDistanceIn(secondsTotal: Int): Int { |
| 29 | + val cycleDuration = flyDuration + restDuration |
| 30 | + val cycles = secondsTotal / cycleDuration |
| 31 | + val remainingFlyDuration = min(secondsTotal - (cycleDuration * cycles), flyDuration) |
| 32 | + return speed * (flyDuration * cycles + remainingFlyDuration) |
| 33 | +} |
| 34 | + |
| 35 | +data class Reindeer(val speed: Int, val flyDuration: Int, val restDuration: Int) |
| 36 | + |
| 37 | +fun List<String>.parse() = map { |
| 38 | + val (speed, flyDuration, restDuration) = it |
| 39 | + .substringAfter(" can fly ") |
| 40 | + .substringBeforeLast(" seconds.") |
| 41 | + .split(" km/s for ", " seconds, but then must rest for ") |
| 42 | + Reindeer(speed.toInt(), flyDuration.toInt(), restDuration.toInt()) |
| 43 | +} |
0 commit comments