Last active
January 22, 2017 20:47
-
-
Save JadenGeller/e7bd0c949d82b3d3814995371713253d to your computer and use it in GitHub Desktop.
Cut a sequence given a predicate taking in successive elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Collection where SubSequence: Sequence, SubSequence.Iterator.Element == Iterator.Element { | |
func cut(atSuccession shouldCut: (Iterator.Element, Iterator.Element) throws -> Bool) rethrows -> [Self.SubSequence] { | |
var (fromIndex, toIndex) = (startIndex, startIndex) | |
var result: [SubSequence] = [] | |
for (x, y) in zip(self, dropFirst()) { | |
defer { toIndex = index(after: toIndex) } | |
guard try shouldCut(x, y) else { continue } | |
result.append(self[fromIndex...toIndex]) | |
fromIndex = index(after: toIndex) | |
} | |
result.append(self[fromIndex...toIndex]) | |
return result | |
} | |
} | |
// Example | |
// print([1, 2, 3, 4, 3, 2, 8, 9, 10, 9, 4, 3, 2].cut(atSuccession: { abs($0 - $1) > 1 })) | |
// -> [ArraySlice([1, 2, 3, 4, 3, 2]), ArraySlice([8, 9, 10, 9]), ArraySlice([4, 3, 2])] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment