Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created March 24, 2015 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/e59a18c3b17926793de6 to your computer and use it in GitHub Desktop.
Save JadenGeller/e59a18c3b17926793de6 to your computer and use it in GitHub Desktop.
Shuffle Array
extension Array {
func shuffled() -> [T] {
var list = self
for i in 0..<(list.count - 1) {
let j = Int(arc4random_uniform(UInt32(list.count - i))) + i
swap(&list[i], &list[j])
}
return list
}
}
// Example
let arr = [1, 2, 3, 4, 5, 6]
println(arr.shuffled()) // -> [6, 3, 1, 5, 4, 2]
println(arr.shuffled()) // -> [5, 2, 1, 4, 6, 3]
println(arr.shuffled()) // -> [2, 3, 4, 6, 5, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment