whats the best way to remove a duplicates, inclusi...
# getting-started
n
whats the best way to remove a duplicates, inclusively, in a list?
Copy code
1
1
2
3
4
should become
Copy code
2
3
4
I was thinking maybe using either
filter
or
groupBy
n
that would return
Copy code
1
2
3
4
r
Oh, I'm sorry. My mistake.
n
np
Copy code
.groupingBy { it }.eachCount().filterValues {
        it == 1
    }.keys
would work, but maybe there's a better way?
a
groupingBy { it }.eachCount()
is a nice shortcut
Copy code
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/enySBykmC
👍 1
oh you got there first haha
an alternative, using
fold()
https://pl.kotl.in/gkH-ClMAW
Copy code
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")
👍 3
p
You'd need to also track those you've discarded or
listOf(1,1,2,3,4,1)
would result in
listOf(1,2,3,4)
again:
Copy code
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)
}
👍 2
a
ah good point, thanks
some tail recursion, for fun https://pl.kotl.in/DSbnvQTKb
Copy code
fun 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)
  }
}
❤️ 3
w
Copy code
fun <T> List<T>.duplicates(): List<T> = filterNot(mutableSetOf<T>()::add)

assert(listOf(2, 3, 4), list - list.duplicates())
🧠 4
k
Feeling some AoC vibes here 👀
advent of code intensifies 3