Last active
December 14, 2015 13:03
-
-
Save erica/182b6f5b3efc28a9301b to your computer and use it in GitHub Desktop.
This file contains 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 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