简体   繁体   English

如何比较两个数组以获得相似对象的数量?

[英]How do you compare two arrays to get the count of similar objects?

I have two string arrays with unique amounts of content and data in each. 我有两个字符串数组,每个字符串数组中的内容和数据量都是唯一的。

I want to be able to find the count of the number of items that appear in both arrays. 我希望能够找到两个数组中出现的项目数的计数

Example: 例:

var array1 = ["Duck", "Dog", "Cat", "Bird", "Elephant", "Cow", "Goat", "Goose"]
var array2 = ["Eagle", "Giraffe", "Cow", "Elephant", "Sheep", "Penguin", "Rhinoceros"]

This should print 2, because Cow and Elephant appear in both array1 and array2. 这应该打印2,因为Cow和Elephant出现在array1和array2中。

My progress is below. 我的进度如下。 This is throwing an error: Closure tuple parameter '(offset: Int, element: (String, String))' does not support destructuring with implicit parameters 这将引发错误: 闭包元组参数'(offset:Int,element:(String,String))'不支持使用隐式参数进行销毁

let compared = zip(array1, array2).enumerated().filter() {
    $1.0.id == $1.1.id
}.count

print(compared)

How do I find the count of items that appear in both arrays? 如何找到两个数组中出现的项目数? Note, there will never be 3 or more arrays. 注意,永远不会有3个或更多的数组。 Always will compare 2 arrays. 始终将比较2个数组。

Maybe you can use Set operation: 也许您可以使用Set操作:

var array1 = ["Duck", "Dog", "Cat", "Bird", "Elephant", "Cow", "Goat", "Goose"]
var array2 = ["Eagle", "Giraffe", "Cow", "Elephant", "Sheep", "Penguin", "Rhinoceros"]

print( Set(array1).intersection(array2).count ) //-> 2

You can create a generic function that returns the common elements of two arrays by returning the intersection of the two Set s created from the Array s. 您可以通过返回从Array创建的两个Set的交集来创建返回两个数组的公共元素的泛型函数。 The Hashable generic type restriction is needed since elements of a Set need to conform to Hashable . 由于Set元素需要符合Hashable因此需要Hashable泛型类型限制。

func commonElements<T:Hashable>(between array1:[T],and array2:[T])->[T]{
    return Array(Set(array1).intersection(Set(array2)))
}

commonElements(between: array1, and: array2) // ["Cow", "Elephant"]

If you are only interested in the number of such elements, you can simply call count on the return value. 如果您仅对此类元素的数量感兴趣,则可以简单地对返回值调用count

commonElements(between: array1, and: array2).count // 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM