检查两个数组中的元素是否相同,与索引无关 [英] Check if elements in two arrays are same irrespective of index

查看:186
本文介绍了检查两个数组中的元素是否相同,与索引无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数组-array1array2

Suppose if I have two arrays - array1 and array2

let array1 = ["abc","pqr","xyz"]
let array2 = ["pqr", "xyz", "abc"]

然后我想要结果为array1等于array2.

Then I want result as array1 is equal to array2.

如果我的数组中有重复的元素

Also if my array has duplicate elements

let array1 = ["abc","pqr","xyz"]
let array2 = ["pqr", "xyz", "abc", "abc", "xyz"]

然后我想要结果为array1不等于array2.

Then I want result as array1 is NOT equal to array2.

搜索后,我发现但是它在目标C中,而isEqualToSet在Swift3中不存在

but it is in Objective C and isEqualToSetis not there in Swift3

推荐答案

使用计数集,如

Using counted sets as in Compare two arrays with the same value but with a different order works in Swift as well:

let set1 = NSCountedSet(array: array1)
let set2 = NSCountedSet(array: array2)
print(set1 == set2)

这对于字符串,数字和其他值非常有效 映射到相应的Foundation类型NSStringNSNumber等. 与自定义结构一起使用时,可能会产生意想不到的结果.

This works well for strings, numbers, and other values which are mapped to corresponding Foundation types NSString, NSNumber, etc. It might give unexpected results when used with custom structs.

对于纯Swift解决方案,计算每个出现的次数 数组中的元素:

For a pure Swift solution, count the number of occurrences of each element in the arrays:

func countMap<T: Hashable>(array: [T]) -> [T: Int] {
    var dict = [T: Int]()
    for elem in array {
        dict[elem] = (dict[elem] ?? 0) + 1
    }
    return dict
}

并比较结果字典:

print(countMap(array: array1) == countMap(array: array2))

或者–如果数组元素为Comparable – 比较排序后的数组:

Alternatively – if the array elements are Comparable – compare the sorted arrays:

print(array1.sorted() == array2.sorted())

这篇关于检查两个数组中的元素是否相同,与索引无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆