Skip to content

Commit 5b29403

Browse files
committed
add solution for 2023/day6
1 parent 6dab8e4 commit 5b29403

File tree

4 files changed

+71
-0
lines changed

4 files changed

+71
-0
lines changed

src/main/kotlin/advent2023/Day06.kt

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package advent2023
2+
3+
private const val COLON_DELIMITER = ":"
4+
5+
class Day06(private val input: List<String>) {
6+
7+
fun solvePart1(): Int {
8+
val times =
9+
input.first().split(COLON_DELIMITER).last().split(" ").filter { it.isNotBlank() }.map { it.toLong() }
10+
val distances =
11+
input.last().split(COLON_DELIMITER).last().split(" ").filter { it.isNotBlank() }.map { it.toLong() }
12+
13+
val timeToDistance = times.mapIndexed { index, time ->
14+
time to distances[index]
15+
}.toMap()
16+
17+
val numberOfWays = computeNumberOfWaysToWin(timeToDistance)
18+
return numberOfWays.reduce { acc, element -> acc * element }
19+
}
20+
21+
fun solvePart2(): Int {
22+
val time = input.first().split(COLON_DELIMITER).last().filter { it.isDigit() }.toLong()
23+
val distance =
24+
input.last().split(COLON_DELIMITER).last().filter { it.isDigit() }.toLong()
25+
val timeToDistance = mapOf(time to distance)
26+
val numberOfWays = computeNumberOfWaysToWin(timeToDistance)
27+
return numberOfWays.reduce { acc, element -> acc * element }
28+
}
29+
30+
private fun computeNumberOfWaysToWin(timeToDistance: Map<Long, Long>): List<Int> {
31+
return timeToDistance.keys.map { time ->
32+
(0..time).map { buttonHoldTime ->
33+
buttonHoldTime * (time - buttonHoldTime)
34+
}.count { distanceTravelled ->
35+
distanceTravelled > (timeToDistance[time] ?: 0)
36+
}
37+
}
38+
}
39+
}
40+
41+
fun main() {
42+
val input = Resources.resourceAsListOfString("advent2023/day06.txt")
43+
val day06 = Day06(input = input)
44+
println("Part 1 Solution: ${day06.solvePart1()}")
45+
println("Part 2 Solution: ${day06.solvePart2()}")
46+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Time: 46 80 78 66
2+
Distance: 214 1177 1402 1024
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package advent2023
2+
3+
import org.assertj.core.api.Assertions.assertThat
4+
import org.junit.jupiter.api.Test
5+
6+
class Day06Test {
7+
8+
private val input = Resources.resourceAsListOfString("advent2023/day06.txt")
9+
10+
@Test
11+
fun `test part 1`() {
12+
val sut = Day06(input = input)
13+
assertThat(sut.solvePart1()).isEqualTo(288)
14+
}
15+
16+
@Test
17+
fun `test part 2`() {
18+
val sut = Day06(input = input)
19+
assertThat(sut.solvePart2()).isEqualTo(71503)
20+
}
21+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Time: 7 15 30
2+
Distance: 9 40 200

0 commit comments

Comments
 (0)