我想计算arr1中的数字出现在arr2中的次数。我尝试过与集合相交,但是我不想删除重复项。
var arr1 = [1,4,5,7]
func compareCount(arr2[Int])-> Int {
//arr2 = 1,1,4,5,6,6,3,9,7,7,7,1,7
return count
//returns 9 as there are 9 elements within arr2 that exist within arr1
}
答案 0 :(得分:4)
您可以使用NSCountedSet
:
var arr1 = [1,4,5,7]
var arr2 = [1,1,4,5,6,6,3,9,7,7,7,1,7]
let countedSet = NSCountedSet(array: arr2)
然后,遍历arr1
,对于每个变量,您将很容易获得count(for:)
的发生次数,而对于reduce,则可以添加它们:
let numberOfOccurences = arr1.reduce(into: 0) { (result, current) in
let numberOfOccurencesForCurrent = countedSet.count(for: current)
result += numberOfOccurencesForCurrent
}
print("numberOfOccurences: \(numberOfOccurences)")
编辑:
如果您不想使用reduce()
(因为您想避免在不理解的情况下使用它),而是做一个更简单的循环:
var numberOfOccurences = 0
arr1.forEach({ numberOfOccurences += countedSet.count(for: $0) })
答案 1 :(得分:2)
环绕第一个数组并计算第二个数组中每个过滤的元素
var count = 0
arr1.forEach( { value in
count += arr2.filter( {$0 == value} ).count
})