Last active
September 15, 2015 15:43
-
-
Save maximbilan/4e1f5e63946b1559af8d to your computer and use it in GitHub Desktop.
Swift Array Shuffle
This file contains 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 Foundation | |
extension CollectionType where Index == Int { | |
func shuffle() -> [Generator.Element] { | |
var list = Array(self) | |
list.shuffleInPlace() | |
return list | |
} | |
} | |
extension MutableCollectionType where Index == Int { | |
mutating func shuffleInPlace() { | |
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]) | |
} | |
} | |
} | |
// Using | |
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
array.shuffleInPlace() | |
print(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment