From c3ea85a5ad0a65df09e448d750c083f9b4a50ac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tristan=20Dani=C3=ABl=20Maat?= Date: Wed, 6 Dec 2023 18:21:42 +0100 Subject: [PATCH] Complete day 6 --- day6/day6.kt | 43 +++++++++++++++++++++++++++++++++++++++++++ day6/input | 2 ++ day6/test | 2 ++ 3 files changed, 47 insertions(+) create mode 100644 day6/day6.kt create mode 100644 day6/input create mode 100644 day6/test diff --git a/day6/day6.kt b/day6/day6.kt new file mode 100644 index 0000000..2575089 --- /dev/null +++ b/day6/day6.kt @@ -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>): 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 { + 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> { + 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) } + } +} diff --git a/day6/input b/day6/input new file mode 100644 index 0000000..e0996e8 --- /dev/null +++ b/day6/input @@ -0,0 +1,2 @@ +Time: 60 80 86 76 +Distance: 601 1163 1559 1300 diff --git a/day6/test b/day6/test new file mode 100644 index 0000000..b39f49d --- /dev/null +++ b/day6/test @@ -0,0 +1,2 @@ +Time: 7 15 30 +Distance: 9 40 200 \ No newline at end of file