Complete day 6

main
Tristan Daniël Maat 2023-12-06 18:21:42 +01:00
parent 13454b3f18
commit c3ea85a5ad
Signed by: tlater
GPG Key ID: 49670FD774E43268
3 changed files with 47 additions and 0 deletions

43
day6/day6.kt Normal file
View File

@ -0,0 +1,43 @@
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) }
}
}

2
day6/input Normal file
View File

@ -0,0 +1,2 @@
Time: 60 80 86 76
Distance: 601 1163 1559 1300

2
day6/test Normal file
View File

@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200