adventofcode-2023/day6/day6.kt

44 lines
1.2 KiB
Kotlin

import java.io.File
import kotlin.text.Regex
fun main() {
val input = File("input")
val races = parseRaces(input)
println(part1(races))
val singleRace = parseSingleRace(input)
println(part1(listOf(singleRace)))
}
fun part1(races: List<Pair<Long, Long>>): Long {
return races.map { getNumberOfWins(it.first, it.second) }.reduce { count, acc -> count * acc }
}
fun getNumberOfWins(time: Long, distance: Long): Long {
val wins = (0..time / 2).filter { it * (time - it) > distance }.count()
return when (time % 2) {
0L -> (wins - 1L) * 2L + 1L
1L -> wins * 2L
else -> throw Exception("Unreachable")
}
}
fun parseSingleRace(input: File): Pair<Long, Long> {
return input.useLines {
val numbers =
it
.map { it.split(':').drop(1).single().filter { it.isDigit() }.toLong() }
.iterator()
Pair(numbers.next(), numbers.next())
}
}
fun parseRaces(input: File): List<Pair<Long, Long>> {
return input.useLines {
val numbers = it.map { it.split(Regex("\\s+")).drop(1).map { it.toLong() } }.iterator()
numbers.next().zip(numbers.next()).map { (time, distance) -> Pair(time, distance) }
}
}