Skip to content

Instantly share code, notes, and snippets.

@tal
Created October 22, 2015 23:10
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 tal/6e72ae99a8f0aa66504f to your computer and use it in GitHub Desktop.
Save tal/6e72ae99a8f0aa66504f to your computer and use it in GitHub Desktop.
extension CollectionType {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension CollectionType where Index == Int {
func sample(count:Int) -> ArraySlice<Generator.Element> {
return shuffle().prefix(count)
}
}
extension CollectionType where Index.Distance == Int {
func sample() -> Generator.Element? {
guard count < 1 else { return nil }
let offset = Int(arc4random_uniform(UInt32(self.count)))
let index = startIndex.advancedBy(offset)
return self[index]
}
}
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment