Skip to content

Instantly share code, notes, and snippets.

@erica
Last active Sep 15, 2015
Embed
What would you like to do?
extension CollectionType {
func generateWithStride(interval: Self.Index.Distance = 1) -> PermutationGenerator<Self,AnySequence<Self.Index>> {
var index = startIndex
let generator: AnyGenerator<Self.Index> = anyGenerator {
// Was:
// let currentIndex = index
// index = currentIndex.advancedBy(interval)
// return currentIndex.distanceTo(self.endIndex) <= 0 ? nil : currentIndex
// http://twitter.com/oisdk/status/643830784026103808
// advancedBy has a limit parameter, so you can avoid the O(n) distanceTo()
// and <. https://gist.github.com/oisdk/d5f46ba03d56c9ec0a89
// http://pic.twitter.com/NbjIdFL8k4
defer { index = index.advancedBy(interval, limit: self.endIndex) }
return index == self.endIndex ? nil : index
}
return PermutationGenerator(elements:self, indices: AnySequence(generator))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment