检查数组中的所有元素都在雨燕相同的值 [英] check if all elements of an array have the same value in Swift

查看:221
本文介绍了检查数组中的所有元素都在雨燕相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有斯威夫特一个函数,检查数组中的所有元素是否具有相同的价值?对我来说,这是键入内部的数组。我知道我可以使用一个简单的for循环,我只是想知道迭代它,如果有是内置的,更快的东西。

Is there a function in Swift that checks whether all elements of an array have the same value? In my case, it's an array of type Int. I know I can iterate over it using a simple for loop I was just wondering if there is something that is built in and quicker.

推荐答案

任何方法都必须遍历所有元素,直到一个不同的元素被发现:

Any method must iterate over all elements until a different element is found:

func allEqualUsingLoop<T : Equatable>(array : [T]) -> Bool {
    if let firstElem = array.first {
        for elem in array {
            if elem != firstElem {
                return false
            }
        }
    }
    return true
}

而不是外在的循环,你可以使用包含()功能:

func allEqualUsingContains<T : Equatable>(array : [T]) -> Bool {
    if let firstElem = array.first {
        return !contains(array, { $0 != firstElem })
    }
    return true
}

如果数组元素哈希(如内部),那么你就可以
创建一个设置(自斯威夫特1.2)从数组元素并检查是否有且只有一个元素。

If the array elements are Hashable (such as Int) then you can create a Set (available since Swift 1.2) from the array elements and check if it has exactly one element.

func allEqualUsingSet<T : Hashable>(array : [T]) -> Bool {
    let uniqueElements = Set(array)
    return count(uniqueElements) <= 1
}

有一个快速的基准测试显示,包含方法比set的方法要快得多
为1,000,000的整数的数组,特别是如果元件是
的人人平等。这很有道理,因为包含()尽快返回
作为非匹配的元素被找到,而设置(阵列)总是
穿过整个阵列

A quick benchmarking test revealed that the "contains" method is much faster than the "set" method for an array of 1,000,000 integers, in particular if the elements are not all equal. This make sense because contains() returns as soon as a non-matching element is found, whereas Set(array) always traverses the entire array.

另外,载的方法同样是快还是比外在的循环速度稍快。

Also the "contains" methods is equally fast or slightly faster than an explicit loop.

下面是一些简单的标杆code。当然的结果可以变化
与阵列大小,不同元件的数量和元素数据类型

Here is some simple benchmarking code. Of course the results can vary with the array size, the number of different elements and the elements data type.

func measureExecutionTime<T>(title: String,  @noescape f : (() -> T) ) -> T {
    let start = NSDate()
    let result = f()
    let end = NSDate()
    let duration = end.timeIntervalSinceDate(start)
    println("\(title) \(duration)")
    return result
}

var array = [Int](count: 1_000_000, repeatedValue: 1)
array[500_000] = 2

let b1 = measureExecutionTime("using loop    ") {
    return allEqualUsingLoop(array)
}

let b2 = measureExecutionTime("using contains") {
    allEqualUsingContains(array)
}

let b3 = measureExecutionTime("using set     ") {
    allEqualUsingSet(array)
}

结果(在MacBook Pro上,发布配置):

Results (on a MacBook Pro, Release configuration):


using loop     0.000651001930236816
using contains 0.000567018985748291
using set      0.0344770550727844

使用数组[1_000] = 2 结果


using loop     9.00030136108398e-06
using contains 2.02655792236328e-06
using set      0.0306439995765686


更新斯威夫特2 / X code 7:由于雨燕的各种变化
语法中,函数现在写为


Update for Swift 2/Xcode 7: Due to various changes in the Swift syntax, the function is now written as

func allEqual<T : Equatable>(array : [T]) -> Bool {
    if let firstElem = array.first {
        return !array.dropFirst().contains { $0 != firstElem }
    }
    return true
}

但你现在也可以将其定义为阵列的扩展方法:

But you can now also define it as an extension method for arrays:

extension Array where Element : Equatable {
    func allEqual() -> Bool {
        if let firstElem = first {
            return !dropFirst().contains { $0 != firstElem }
        }
        return true
    }
}

print([1, 1, 1].allEqual()) // true
print([1, 2, 1].allEqual()) // false

这篇关于检查数组中的所有元素都在雨燕相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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