Nick
02/09/2023, 10:03 PM1
1
2
3
4
should become
2
3
4
I was thinking maybe using either filter
or groupBy
Russell Stewart
02/09/2023, 10:07 PMdistinct()
or distinctBy()
.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/distinct.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/distinct-by.htmlNick
02/09/2023, 10:08 PM1
2
3
4
Russell Stewart
02/09/2023, 10:09 PMNick
02/09/2023, 10:09 PM.groupingBy { it }.eachCount().filterValues {
it == 1
}.keys
would work, but maybe there's a better way?Adam S
02/09/2023, 10:11 PMgroupingBy { it }.eachCount()
is a nice shortcut
val list = listOf(1, 1, 2, 3, 4)
val counts: Map<Int, Int> = list.groupingBy { it }.eachCount()
println("counts $counts")
val singles: Set<Int> = counts.filterValues { it == 1 }.keys
println("singles $singles")
https://pl.kotl.in/enySBykmCfold()
https://pl.kotl.in/gkH-ClMAW
val list = listOf(1, 1, 2, 3, 4)
val singles = list.fold(emptySet<Int>()) { acc, i ->
when (i) {
in acc -> acc - i
else -> acc + i
}
}
println("singles $singles")
phldavies
02/09/2023, 10:23 PMlistOf(1,1,2,3,4,1)
would result in listOf(1,2,3,4)
again:
val list = listOf(1,1,2,3,4,1)
fun main() {
val result = list.fold(emptySet<Int>() to emptySet<Int>()) { (kept, rejected), v ->
when(v) {
in kept -> (kept - v) to (rejected + v)
in rejected -> kept to rejected
else -> (kept + v) to rejected
}
}.first
println(result)
}
Adam S
02/09/2023, 10:28 PMfun main() {
val list = listOf(1, 1, 2, 3, 4, 1)
val singles = list.removeDuplicates()
println("singles $singles")
}
tailrec fun Collection<Int>.removeDuplicates(
valid: Set<Int> = emptySet(),
seen: Set<Int> = emptySet(),
): Set<Int> {
return when (val first = firstOrNull()) {
null -> valid
in seen -> (this - first).removeDuplicates(valid - first, seen + first)
else -> (this - first).removeDuplicates(valid + first, seen + first)
}
}
Wout Werkman
02/10/2023, 10:33 AMfun <T> List<T>.duplicates(): List<T> = filterNot(mutableSetOf<T>()::add)
assert(listOf(2, 3, 4), list - list.duplicates())
Kevin Del Castillo
02/10/2023, 2:25 PM