-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay06WaitForIt.kt
41 lines (34 loc) · 1.15 KB
/
Day06WaitForIt.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package adventofcode.year2023
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.product
import kotlin.math.ceil
import kotlin.math.pow
import kotlin.math.sqrt
class Day06WaitForIt(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override fun partOne(): Long {
val (times, distances) =
input
.lines()
.map { line -> line.split(" ").mapNotNull(String::toLongOrNull) }
return times
.zip(distances)
.map { it.countWaysToWin() }
.product()
}
override fun partTwo() =
input
.lines()
.map { line -> line.filter(Char::isDigit).toLong() }
.zipWithNext()
.first()
.countWaysToWin()
companion object {
private fun Pair<Long, Long>.countWaysToWin(): Long {
val (time, distance) = this
val lower = (0.5 * (time - sqrt(time.toDouble().pow(2) - 4 * distance)) + 1).toLong()
val upper = ceil(0.5 * (sqrt(time.toDouble().pow(2) - 4 * distance) + time) - 1).toLong()
return upper - lower + 1
}
}
}