Skip to content

Instantly share code, notes, and snippets.

@tartakovsky
Last active October 31, 2016 00:22
Show Gist options
  • Select an option

  • Save tartakovsky/10b0b5adf8b2df3a6c17 to your computer and use it in GitHub Desktop.

Select an option

Save tartakovsky/10b0b5adf8b2df3a6c17 to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle in Swift.
Source: http://stackoverflow.com/a/24029847/1855792 by Nate Cook
Implementation of Fisher-Yates (fast and uniform) shuffle for any collection type using Swift 2 Protocol Extensions.
The naming and behavior follow Swift 2.0's sort() and sortInPlace() methods.
Code:
See FisherYatesShuffle.swift file
Usage:
[1, 2, 3].shuffle()
// [2, 3, 1]
let fiveStrings = 0.stride(through: 100, by: 5).map(String.init).shuffle()
// ["20", "45", "70", "30", ...]
var numbers = [1, 2, 3, 4]
numbers.shuffleInPlace()
// [3, 2, 1, 4]
extension CollectionType {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
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