Skip to content

Instantly share code, notes, and snippets.

@erica
Last active September 15, 2015 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/8e99de9c113003d390d7 to your computer and use it in GitHub Desktop.
Save erica/8e99de9c113003d390d7 to your computer and use it in GitHub Desktop.
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