-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay05.kt
67 lines (56 loc) · 2.47 KB
/
Day05.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
59
60
61
62
63
64
65
66
67
private fun foldMappings(
maps: List<List<Pair<Long, Interval>>>,
initialIntervals: List<Interval>,
): Long =
maps.fold(initialIntervals) { intervals, mappings ->
intervals.flatMap { initialFromRange ->
val resultRanges = mutableListOf<Interval>()
val leftRanges = mappings.fold(listOf(initialFromRange)) { fromRanges, (destination, source) ->
fromRanges.flatMap { current ->
when {
current in source -> {
resultRanges += current - source.start + destination
sequenceOf()
}
source in current -> {
resultRanges += Interval(0, source.size) + destination
sequenceOf(
Interval(current.start, source.start - 1),
Interval(source.end + 1, current.end),
)
}
current.start in source -> {
resultRanges += Interval(current.start - source.start, source.size) + destination
sequenceOf(Interval(source.end + 1, current.end))
}
current.end in source -> {
resultRanges += Interval(0, current.end - source.start) + destination
sequenceOf(Interval(current.start, source.start - 1))
}
else -> sequenceOf(current)
}
}
}
resultRanges + leftRanges
}
}.minOf { it.start }
fun main() {
val (seedsString, mapString) = getFullInput().split("\n\n", limit = 2)
val seeds = seedsString.substringAfter(":").toLongs()
val maps = mapString.splitToSequence("\n\n")
.map { block ->
block.lines()
.asSequence()
.drop(1)
.map {
val (destination, source, range) = it.toLongs()
destination to Interval(source, source + range - 1)
}
.toList()
}
.toList()
val first = foldMappings(maps, seeds.map { Interval(it) })
val seedIntervals = seeds.asSequence().chunked(2).map { (a, b) -> Interval(a, a + b - 1) }.toList()
val second = foldMappings(maps, seedIntervals)
println("$first $second")
}