Is there a short & clean way to compare 2 arrays of sorted Int
?
Like [1,4,7]
should come before [1,5]
but after [1,2,3
A possible implementation (explanations inline):
func < <T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
// Compare all elements up to common length, return
// if a difference is found:
for (l, r) in zip(lhs, rhs) {
if l < r { return true }
if l > r { return false }
}
// All common elements are equal, check if rhs is "longer":
return lhs.count < rhs.count
}
Example:
print([1,4,7] < [1,5]) // true
print([1,4,7] < [1,2,3,8]) // false
print([1,4,7] < [1,4,7,8]) // true (left array is shorter)
print([1,4,7] < [1,4,7]) // false (arrays are equal)