gpt4 book ai didi

collections - 在 Kotlin 中维护重复值的两个列表的交集

转载 作者:行者123 更新时间:2023-12-02 13:03:14 25 4
gpt4 key购买 nike

我想在不消除重复项的情况下找到两个列表之间的共同元素的数量。

例如:

输入:[1, 3, 3] & [4, 3, 3]
输出:2 , 因为共同的元素是 [3, 3]
输入:[1, 2, 3] & [4, 3, 3]
输出:1 , 因为共同的元素是 [3]
如果我使用 Kotlin 集合 intersect ,结果是一个集合,这将阻止我计算重复值。

我发现(对于 Python)this ,以不同方式处理重复项和 this ,这导致我使用 this实现,其中 ab是列表:

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))
}

然而,作为 Kotlin 的新手,我想知道是否有更“Kotlin-y”的方式来做到这一点——利用 Kotlin 的所有集合功能?也许是避免显式迭代的东西?

最佳答案

这:

val a = listOf(1, 2, 3, 3, 4, 5, 5, 5, 6)
val b = listOf(1, 3, 3, 3, 4, 4, 5, 6, 6, 7)

var counter = 0

a.intersect(b).forEach { x -> counter += listOf(a.count {it == x}, b.count {it == x}).min()!! }

println(counter)

将打印
6

它使用 2 个列表的交集并通过遍历其中的每个项目,向计数器添加项目在两个列表中的最小出现次数。
通过此导入:
import kotlin.math.min

您可以避免在每次迭代时创建列表并简化为:
a.intersect(b).forEach { x-> counter += min(a.count {it == x}, b.count {it == x}) } 

由 Arjan 提供,一种更优雅的计算总和的方法:
val result = a.intersect(b).map { x -> min(a.count {it == x}, b.count {it == x}) }.sum()

关于collections - 在 Kotlin 中维护重复值的两个列表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com