Tomasz Krakowiak
03/31/2021, 9:49 AMelizarov
03/31/2021, 7:37 PMTomasz Krakowiak
04/01/2021, 2:57 PMprivate fun <T> MutableList<T>.swapRanges(aRange: IntRange, bRange: IntRange) {
val (firstRange, lastRange) = (aRange to bRange).sort { a, b -> a.first.compareTo(b.first) }
val firstRegionView = subList(firstRange.first, firstRange.last + 1)
val firstRegionCopy = ArrayList(firstRegionView)
val secondRegionView = subList(lastRange.first, lastRange.last + 1)
val secondRegionCopy = ArrayList(secondRegionView)
firstRegionView.clear()
secondRegionView.clear()
firstRegionView.addAll(secondRegionCopy)
secondRegionView.addAll(firstRegionCopy)
}
Pair.swap() I use in Pair.sort()
private fun <T> Pair<T, T>.sort(comparator: Comparator<T>) : Pair<T,T> {
val compare = comparator.compare(first, second)
return if(compare <= 0) {
this
} else {
this.swap()
}
}
We can also use Pairs to represent non-directional graphs edges and normalize them using sort to represent 2 element nodes set.
I encountered quite a few cases when I wanted to sort Pair's. If you're developer I guess you can imagine quite a lot of use-cases as well : ) But in general Pairs and Triples and other tuples can often be used as efficient fixed size collection/list implementations.elizarov
04/01/2021, 3:00 PMTomasz Krakowiak
04/01/2021, 3:58 PMZhelenskiy
04/01/2021, 7:41 PMList<T>
interface for tuples of the one type as described in KT-45587 (Tuples (structural literals and structural types) by me would make such functions (Pair.sorted()
) possible.Tomasz Krakowiak
04/01/2021, 8:07 PMelizarov
04/02/2021, 11:32 AMZhelenskiy
04/02/2021, 12:07 PMelizarov
04/02/2021, 1:49 PMList
interface) does not make much sense.Zhelenskiy
04/02/2021, 1:53 PMelizarov
04/02/2021, 1:57 PMelizarov
04/02/2021, 1:59 PMZhelenskiy
04/02/2021, 2:02 PM