Skip to content

Instantly share code, notes, and snippets.

@erica
Last active December 14, 2015 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erica/182b6f5b3efc28a9301b to your computer and use it in GitHub Desktop.
Save erica/182b6f5b3efc28a9301b to your computer and use it in GitHub Desktop.
extension CollectionType {
/// create a lazy succession of randomly ordered indices
///
/// - returns: random index generator
func scrambledIndexGenerator() -> AnyGenerator<Self.Index> {
/// The original indices
var indexArray = Array(indices)
/// The boundary separating available and consumed indices
var endBoundary: Int = numericCast(count)
/// Build a genetor
return anyGenerator {
/// Generator completes when indices are exhausted
if endBoundary == 0 {return nil}
/// Randomly select the next location in the
/// array of indices to use and adjust the boundary
let nextIndexIndex = Int(arc4random_uniform(UInt32(endBoundary)))
/// Fetch the index
let nextIndex = indexArray[Int(nextIndexIndex)]
/// Adjust the boundary
endBoundary -= 1
/// Move the consumed index after the boundary
if nextIndexIndex != endBoundary {
swap(&indexArray[nextIndexIndex], &indexArray[endBoundary])
}
/// Return the index
return nextIndex
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment