-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day6.kt
58 lines (51 loc) · 1.59 KB
/
Day6.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package aoc2023.day06
fun parse(lines: List<String>): List<RaceData> {
val races = mutableListOf<RaceData>()
val times = lines[0]
.replace("Time:", "")
.trim()
.split("\\s+".toRegex())
.map { it.toInt() }
val distances = lines[1]
.replace("Distance:", "")
.trim()
.split("\\s+".toRegex())
.map { it.toInt() }
times.indices.forEach { i ->
races.add(RaceData(times[i], distances[i]))
}
return races
}
fun part1(races: List<RaceData>): Int {
val results = mutableListOf<Int>()
races.forEach { race ->
var winningPossibilities = 0
(0..race.time).forEach { t ->
val distance = computeDistance(race.time.toLong(), t.toLong())
if (distance > race.distance) {
winningPossibilities++
}
}
results.add(winningPossibilities)
}
return results.reduce { acc, elem ->
acc * elem
}
}
fun part2(races: List<RaceData>): Long {
val time = races.joinToString("") { it.time.toString() }.toLongOrNull() ?: -1L
val distance = races.joinToString("") { it.distance.toString() }.toLongOrNull() ?: -1L
var winningPossibilities = 0L
(0..time).forEach { t ->
val currentDistance = computeDistance(time, t)
if (currentDistance > distance) {
winningPossibilities++
}
}
return winningPossibilities
}
fun computeDistance(time: Long, initSpeed: Long): Long {
val availTime = time - initSpeed
return availTime * initSpeed
}
data class RaceData(val time: Int, val distance: Int)