I want to write a custom operation on a sorted Array
(or Collection
or Sequence
, whatever) that does the following:
Starting from the beginning, it looks at each adjacent pair of elements. If the condition is met among the two, move on to the next pair, otherwise split it. So in the end, I would have an array of arrays, where the condition is satisfied among the elements within the same subarray, but not between different subarrays. Is the following correct and efficient?
extension Array {
public func splitSorted(by condition: (Element, Element)->(Bool)) -> [[Element]] {
var result = [[Element]]()
var start = 0
var end = 0
while end != self.count - 1 {
while end < self.count && condition(self[start], self[end]) {
end += 1
}
result.append(Array(self[start..<end]))
start = end
}
return result
}
}