I want to find the number of common elements between two lists without eliminating duplicates.
For example:
input: [1, 3, 3]
& [4, 3, 3]
output: 2
, since the common elements are [3, 3]
input: [1, 2, 3]
& [4, 3, 3]
output: 1
, since the common elements are [3]
If I were to use the Kotlin collections intersect, the result is a set, which will prevent me from counting duplicate values.
I found (for Python) this, which handles duplicates differently and this, which led me to use this implementation, where a
and b
are the lists:
val aCounts = a.groupingBy { it }.eachCount()
val bCounts = b.groupingBy { it }.eachCount()
var intersectionCount = 0;
for ((k, v) in aCounts) {
intersectionCount += Math.min(v, bCounts.getOrDefault(k, 0))
}
However, being new to Kotlin I'm wondering if there's a more "Kotlin-y" way to do this--something taking advantage of all Kotlin's collections functionality? Maybe something that avoids explicitly iterating?