Created
March 24, 2015 07:55
-
-
Save JadenGeller/e59a18c3b17926793de6 to your computer and use it in GitHub Desktop.
Shuffle Array
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
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