generated from kotlin-hands-on/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay01.kt
42 lines (35 loc) · 1.16 KB
/
Day01.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
package year2022.`01`
import readInput
fun main() {
fun prepareListOfElfsWithCalories(input: List<String>): List<List<Int>> {
return input
// Null is for empty strings that are separators.
.map { it.toIntOrNull() }
.fold(mutableListOf(mutableListOf<Int>())) { listOfElfs, product ->
if (product == null) {
listOfElfs.add(mutableListOf())
} else {
listOfElfs.last().add(product)
}
listOfElfs
}
}
fun part1(input: List<String>): Int {
return prepareListOfElfsWithCalories(input)
.maxOfOrNull { it.sum() }
?: error("Illegal state")
}
fun part2(input: List<String>): Int {
return prepareListOfElfsWithCalories(input)
.map { it.sum() }
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}