将Array与最多100个项目ID 's (containing duplicates) to array with unique id'进行比较

我想计算来自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
}

回答(2)

2 years ago

您可以使用 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) })

2 years ago

循环第一个数组并计算第二个数组中的每个过滤元素

var count = 0
arr1.forEach( { value in
    count += arr2.filter( {$0 == value} ).count
})