首页 文章

如何从具有重复范围的数组中获取具有唯一范围的数组?

提问于
浏览
2

我可以从具有重复数字的数组中获得一组唯一数字

let arrayWithReapeats = [1, 2, 3, 7, 3]
let unique = Array(Set(arrayWithReapeats))

我需要一个具有独特范围的阵列

Range<String.Index>

从具有重复范围的阵列,例如像这样 .

let arrayWithReapeatsIdexes = [1..<5, 3..<9, 9..<25, 3..<9]

我不能对Set使用相同的方法,因为默认情况下只有String,Int,Double和Bool可以使用 . 如何使范围可以使用上述方法?

2 回答

  • 2

    哈希值的唯一要求是

    x == y表示x.hashValue == y.hashValue

    这意味着“琐碎”的哈希函数

    extension Range : Hashable {
        public var hashValue: Int {
            return 0
        }
    }
    

    是有效的,有效:

    let arrayWithRepeatingIndexes = [1..<5, 3..<9, 9..<25, 3..<9]
    let arrayWithUniqueIndexes = Array(Set(arrayWithRepeatingIndexes))
    
    print(arrayWithUniqueIndexes)
    // [Range(1..<5), Range(3..<9), Range(9..<25)]
    

    您还可以使用以下事实:从开始到结束索引的距离是整数类型(因此具有哈希值):

    public var hashValue: Int {
        return startIndex.distanceTo(endIndex).hashValue
    }
    

    或者从描述字符串中计算哈希值(例如“3 .. <9”):

    public var hashValue: Int {
        return description.hashValue
    }
    

    你必须弄清楚哪一个对你的目的最有效 .

  • 1

    试试这个:

    extension SequenceType where Generator.Element: Equatable {
        func unique() -> [Generator.Element] {
        var seen: Array<Generator.Element> = []
            return  filter {
            if seen.contains($0){
                return false
            } else {
                seen.append($0)
                return true
            }
        }
        }
    }
    

相关问题