Last active
August 29, 2015 14:27
-
-
Save lilyball/8738524e0243a93376ed to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle for Swift
This file contains hidden or 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
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