-
-
Save ilyannn/ee39ce0c20155d40b48c 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
// TODO: insert guards to use open-source version of random() if necessary | |
func random(x: Int) -> Int { | |
return Int(arc4random_uniform(UInt32(endBoundary))) | |
} | |
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 = indexArray.count | |
/// Build a genetor | |
return anyGenerator { | |
/// Generator completes when indices are exhausted | |
guard endBoundary > 0 else {return nil} | |
/// Randomly select the next location in the | |
/// array of indices to use and adjust the boundary | |
let nextIndexIndex = random(endBoundary) | |
/// Adjust the boundary | |
endBoundary -= 1 | |
/// Move the consumed index after the boundary | |
if nextIndexIndex != endBoundary { | |
swap(&indexArray[nextIndexIndex], &indexArray[endBoundary]) | |
} | |
/// Return the index | |
return indexArray[endBoundary] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment