Skip to content

Instantly share code, notes, and snippets.

@lilyball
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lilyball/8738524e0243a93376ed to your computer and use it in GitHub Desktop.
Save lilyball/8738524e0243a93376ed to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle for Swift
import Darwin // for arc4random_uniform
extension SequenceType {
@warn_unused_result(mutable_variant="shuffleInPlace") func shuffle() -> [Generator.Element] {
// this is more efficient than building an array and shuffling it
// and it works on sequences too!
var ary: [Generator.Element] = []
ary.reserveCapacity(underestimateCount())
for var x in self {
let j = Int(arc4random_uniform(UInt32(ary.count+1)))
if j != ary.count {
swap(&x, &ary[j])
}
ary.append(x)
}
return ary
}
}
extension MutableCollectionType where Index: RandomAccessIndexType {
mutating func shuffleInPlace() {
for i: Index in startIndex..<advance(endIndex, -2, startIndex) {
let j: Index.Distance = numericCast(arc4random_uniform(numericCast(i.distanceTo(endIndex))))
swap(&self[i], &self[i.advancedBy(j)])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment