Skip to content

Instantly share code, notes, and snippets.

@ilyannn
Forked from erica/byePostfixDecrement.swift
Last active December 14, 2015 13:15
Show Gist options
  • Save ilyannn/ee39ce0c20155d40b48c to your computer and use it in GitHub Desktop.
Save ilyannn/ee39ce0c20155d40b48c to your computer and use it in GitHub Desktop.
// 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