refactor: simplify the solution for the 5th day of AOC

This commit is contained in:
Ivan R. 2024-02-05 00:32:44 +05:00
parent ecaf90adb4
commit 8d2d26c503
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C

View file

@ -51,65 +51,36 @@ class Solution05(lines: List<String>) {
ranges.add(LongRange(seeds[i], seeds[i] + seeds[i+1] - 1))
}
for (map in maps) {
var minCheckedValue = Long.MIN_VALUE
val newList = mutableListOf<LongRange>()
for (mapper in map.mappers.sortedBy{it.sourceRangeStart}) {
//
val mapperEnd = mapper.sourceRangeStart + mapper.rangeLength - 1
val diff = mapper.destRangeStart - mapper.sourceRangeStart
// find all values before this range.
val unmatchedValues = ranges
.filter{it.first < mapper.sourceRangeStart}
.map{LongRange(max(minCheckedValue, it.first), min(mapper.sourceRangeStart - 1, it.last))}
.map{
LongRange(
max(minCheckedValue, it.first),
min(mapper.sourceRangeStart - 1, it.last),
)
}
.filter{it.first <= it.last}
newList.addAll(unmatchedValues)
// map values
val overlappingLeftValues = ranges
.filter{it.first < mapper.sourceRangeStart && it.last >= mapper.sourceRangeStart && it.last <= mapperEnd}
.map{
LongRange(
max(mapper.sourceRangeStart, it.first) + diff,
it.last + diff,
)
}
.filter{it.first <= it.last}
newList.addAll(overlappingLeftValues)
val overlappingMiddleValues = ranges
.filter{it.first >= mapper.sourceRangeStart && it.last <= mapperEnd}
.map{
LongRange(
it.first + diff, it.last + diff
)
}
.filter{it.first <= it.last}
newList.addAll(overlappingMiddleValues)
val overlappingRightValues = ranges
.filter{it.first >= mapper.sourceRangeStart && it.first <= mapperEnd && it.last >= mapperEnd}
.map{
LongRange(
it.first + diff,
min(it.last, mapperEnd) + diff
)
}
.filter{it.first <= it.last}
newList.addAll(overlappingRightValues)
val bigRanges = ranges
.filter{it.first < mapper.sourceRangeStart && it.last > mapperEnd}
.map{
LongRange(
mapper.sourceRangeStart + diff, mapperEnd + diff
)
}
.filter{it.first <= it.last}
newList.addAll(bigRanges)
newList.addAll(
ranges
.map{
LongRange(
max(mapper.sourceRangeStart, it.first) + diff,
min(mapperEnd, it.last) + diff,
)
}
.filter{it.first <= it.last}
)
minCheckedValue = mapperEnd + 1
}