Tim*_*qua 0 arrays comparison swift
在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
Run Code Online (Sandbox Code Playgroud)
有什么方法可以改善比较函数的主体?
修复Leo Dabus指出的崩溃并包括Martin 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 }
}
Run Code Online (Sandbox Code Playgroud)
您的比较功能可以写成
func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
return lhs.count < rhs.count || !zip(lhs, rhs).contains { $0 > $1 }
}
Run Code Online (Sandbox Code Playgroud)
这里zip()返回两个数组中的对的枚举,然后检查第一个数组中的一个元素是否大于第二个数组中的相应元素.
这为您的所有测试用例提供了相同的结果.
正如@Leo正确注意到的那样,如果第一个数组的元素多于第二个数组,则函数会崩溃.有了zip(),额外的元素被忽略了.
备注:如果第一个数组较长,比较应返回false,则可以将其写为
return lhs.count <= rhs.count && (lhs.count < rhs.count || !zip(lhs, rhs).contains { $0 > $1 })
Run Code Online (Sandbox Code Playgroud)