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)) ranges.add(LongRange(seeds[i], seeds[i] + seeds[i+1] - 1))
} }
for (map in maps) { for (map in maps) {
var minCheckedValue = Long.MIN_VALUE var minCheckedValue = Long.MIN_VALUE
val newList = mutableListOf<LongRange>() val newList = mutableListOf<LongRange>()
for (mapper in map.mappers.sortedBy{it.sourceRangeStart}) { for (mapper in map.mappers.sortedBy{it.sourceRangeStart}) {
//
val mapperEnd = mapper.sourceRangeStart + mapper.rangeLength - 1 val mapperEnd = mapper.sourceRangeStart + mapper.rangeLength - 1
val diff = mapper.destRangeStart - mapper.sourceRangeStart val diff = mapper.destRangeStart - mapper.sourceRangeStart
// find all values before this range. // find all values before this range.
val unmatchedValues = ranges val unmatchedValues = ranges
.filter{it.first < mapper.sourceRangeStart} .map{
.map{LongRange(max(minCheckedValue, it.first), min(mapper.sourceRangeStart - 1, it.last))} LongRange(
max(minCheckedValue, it.first),
min(mapper.sourceRangeStart - 1, it.last),
)
}
.filter{it.first <= it.last} .filter{it.first <= it.last}
newList.addAll(unmatchedValues) newList.addAll(unmatchedValues)
// map values // map values
val overlappingLeftValues = ranges newList.addAll(
.filter{it.first < mapper.sourceRangeStart && it.last >= mapper.sourceRangeStart && it.last <= mapperEnd} ranges
.map{ .map{
LongRange( LongRange(
max(mapper.sourceRangeStart, it.first) + diff, max(mapper.sourceRangeStart, it.first) + diff,
it.last + diff, min(mapperEnd, it.last) + diff,
) )
} }
.filter{it.first <= it.last} .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)
minCheckedValue = mapperEnd + 1 minCheckedValue = mapperEnd + 1
} }