2016-01-21 77 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',但我無法使它工作。搜索如何「合併」這樣的數組只能得到數組連接的例子。我在看'減少'和'加入',但他們聽起來不太合適。太棒了。 –