https://kotlinlang.org logo
#stdlib
Title
# stdlib
o

Orhan Tozan

06/17/2022, 1:00 PM
What is the easiest way to get a diff of two `List<Int>`'s?
minus()
won't do it, since
list2 - list1
only shows what
list2
has what
list1
hasn't.
Or maybe I should just use minus() twice, list2 - list1 and list1 - list2
Think I'm going to do that, thanks guys
k

Klitos Kyriacou

06/17/2022, 1:22 PM
rubber duck
e

ephemient

06/17/2022, 2:38 PM
Copy code
fun <T> diffCounts(a: Iterable<T>, b: Iterable<T>): Map<T, Int> = buildMap {
    for (elem in a) put(elem, getOrElse(elem) { 0 } + 1)
    for (elem in b) put(elem, getOrElse(elem) { 0 } - 1)
    values.removeAll(setOf(0))
}
n

nkiesel

06/17/2022, 7:36 PM
Would a `list2.zip(list1).map { it.first - it.second }`not suffice?
e

ephemient

06/17/2022, 7:38 PM
@nkiesel that performs a completely different operation.
Copy code
listOf(1, 2, 3) - listOf(2, 3, 4) == listOf(1)
diffCounts(listOf(1, 2, 3), listOf(2, 3, 4)) == mapOf(1 to 1, 4 to -1)
listOf(2, 3, 4).zip(listOf(1, 2, 3)) { first, second -> first - second } == listOf(1, 1, 1)
n

nkiesel

06/17/2022, 7:56 PM
I guess it was not clear to me what "diff of two `List<Int>`" was asking for. I my view, both interpretations would make sense.
e

ephemient

06/17/2022, 7:57 PM
since the follow-up message was that
list2 - list1
and
list1 - list2
together were useful for OP, I think it was clear which interpretation they meant
n

nkiesel

06/17/2022, 8:04 PM
touché
2 Views