2016-01-21 72 views
0

在Swift中,我有两个从最大到最小排序的数组,这意味着数组的值是Comparable。我想定义一种比较两个数组的自定义方式来表示一个“小于”另一个。一个数组较少的数组总是小于一个较大的数组。我提出的工作很好,但运营商似乎太笨重。它只是觉得应该有一些方法来压缩它,或者有一个内置函数或者内置函数的组合,以实现我想要的功能。这是我有什么:有没有更好的方法来比较两个排序的数组?

func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool { 
    if lhs.count < rhs.count { 
    return true 
    } 

    for i in 0..<lhs.count { 
    if lhs[i] > rhs[i] { 
     return false 
    } 
    } 

    return true 
} 

let first = [9, 8, 7, 6, 4] 
let second = [9, 8, 7, 6, 5] 
let third = [8, 7, 6, 5, 4] 
let fourth = [9, 8, 7, 6] 

let firstSecondComp: Bool = first < second // true 
let secondFirstComp: Bool = second < first // false 
let secondThirdComp: Bool = second < third // false 
let thirdSecondComp: Bool = third < second // true 
let firstThirdComp: Bool = first < third  // false 
let thirdFirstComp: Bool = third < first  // true 

let fourthFirstComp: Bool = fourth < first // true 
let fourthSecondComp: Bool = fourth < second // true 
let fourthThirdComp: Bool = fourth < third // true 

任何方式来改善比较功能的主体?

编辑

固定崩溃所指出的狮子座Dabus和包括马丁的r答案:

func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool { 
    if lhs.count < rhs.count { 
    return true 
    } 
    else if lhs.count > rhs.count { 
    return false 
    } 

    return !zip(lhs, rhs).contains { $0 > $1 } 
} 
+2

请注意,如果你的第一个数组有多个元素,比第二'lhs.count> rhs.count“会使你的应用崩溃 –

+0

好的观察!完全滑过我。 –

回答

6

你比较功能可以写成

func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool { 

    return lhs.count < rhs.count || !zip(lhs, rhs).contains { $0 > $1 } 
} 

这里zip()返回的枚举来自 阵列的对,然后检查是否从第一个 数组大于第二个数组中的相应元素。

这给出了所有测试用例的相同结果。

由于@Leo正确注意到,如果第一个 数组的元素多于第二个元素,那么您的函数将崩溃。 zip(), 额外的元素被忽略。

注:如果比较应该返回false,如果第一个数组较长 那么你可以把它写成

return lhs.count <= rhs.count && (lhs.count < rhs.count || !zip(lhs, rhs).contains { $0 > $1 }) 
+0

非常优雅 - 我被卡在/ indexOf而不是想着'contains':/ – luk2302

+0

超级优雅!我使用超长的地图过滤器bleh卡住了。 – dfri

+0

ZIP!我看着'zip',但我无法使它工作。搜索如何“合并”这样的数组只能得到数组连接的例子。我在看'减少'和'加入',但他们听起来不太合适。太棒了。 –