Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Forked from natecook1000/shuffle.swift
Created November 27, 2015 02:04
Show Gist options
  • Save onmyway133/156fac253739f8d1f4b5 to your computer and use it in GitHub Desktop.
Save onmyway133/156fac253739f8d1f4b5 to your computer and use it in GitHub Desktop.
Swift 2.0 shuffle / shuffleInPlace
// (c) 2015 Nate Cook, licensed under the MIT license
//
// Fisher-Yates shuffle as protocol extensions
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])
}
}
}
[1, 2, 3].shuffle()
// [2, 3, 1]
let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffle()
// ["20", "45", "70", "30", ...]
var numbers = [1, 2, 3, 4]
numbers.shuffleInPlace()
// [3, 2, 1, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment