Ryan Rolnicki
11/28/2021, 3:34 PMRyan Rolnicki
11/28/2021, 4:16 PMfun <T, R : Comparable<R>> Iterable<T>.minBy(n: Int, selector: (T) -> R): List<T> {
val buffer = sortedSetOf<Pair<R, T>>(compareBy { it.first })
for (el in this) {
buffer += selector(el) to el
if (buffer.size > n) {
buffer.remove(buffer.last())
}
}
return buffer.map { it.second }
}
Dominaezzz
11/28/2021, 4:29 PMRyan Rolnicki
11/28/2021, 5:14 PMDominaezzz
11/28/2021, 5:16 PMRyan Rolnicki
11/28/2021, 5:33 PMDominaezzz
11/28/2021, 5:35 PMn
.Ryan Rolnicki
11/28/2021, 5:36 PMKlitos Kyriacou
11/28/2021, 6:14 PMsortedSetOf<Pair<R, T>>(compareBy { it.first })
, why not just use sortedMapOf<R, T>()
?Ryan Rolnicki
11/28/2021, 10:49 PMKlitos Kyriacou
11/28/2021, 11:35 PMSortedSet<Pair<R, T>>
won't work either, since it won't store entries with the same it.first
value. It has exactly the same problem that a Map would have.Ryan Rolnicki
11/28/2021, 11:58 PMYoussef Shoaib [MOD]
12/12/2021, 4:01 PMDominaezzz
12/12/2021, 4:14 PMYoussef Shoaib [MOD]
12/12/2021, 4:40 PMSequence.sortedBy
was lazy but sadly it just converts the underlying iterator to a mutable list and sorts that
(stdlib):
public fun <T> Sequence<T>.sortedWith(comparator: Comparator<in T>): Sequence<T> {
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
val sortedList = this@sortedWith.toMutableList()
sortedList.sortWith(comparator)
return sortedList.iterator()
}
}
}
Dominaezzz
12/12/2021, 4:42 PM