Last active
December 24, 2018 21:55
-
-
Save ijoshsmith/5e3c7d8c2099a3fe8dc3 to your computer and use it in GitHub Desktop.
Randomly shuffle a Swift 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
import Foundation | |
extension Array | |
{ | |
/** Randomizes the order of an array's elements. */ | |
mutating func shuffle() | |
{ | |
for _ in 0..<10 | |
{ | |
sort { (_,_) in arc4random() < arc4random() } | |
} | |
} | |
} | |
var organisms = [ | |
"ant", "bacteria", "cougar", | |
"dog", "elephant", "firefly", | |
"goat", "hedgehog", "iguana"] | |
println("Original: \(organisms)") | |
organisms.shuffle() | |
println("Shuffled: \(organisms)") |
if an array have more than 1024 (2^10) items, this method would be inappropriate.
extension Array {
mutating func shuffle() {
for _ in 0..<((count>0) ? (count-1) : 0) {
sort { (_,_) in arc4random() < arc4random() }
}
}
}
Quite helpful! Thanks!
why organisms? hahaha. Thanks tho!
@ZhipingYang Why not just this?
/**
Extend array to enable random shuffling
*/
extension Array {
/**
Randomizes the order of an array's elements
*/
mutating func shuffle() {
for _ in 0..<count {
sort { (_,_) in arc4random() < arc4random() }
}
}
}
Or this:
extension Array {
mutating func shuffle() {
for _ in indices {
sort { (_,_) in arc4random() < arc4random() }
}
}
}
@jakerockland Be careful with time complexity!
0..<count means O(n)
sort means O(nlogn)
Total complexity is O(n^2logn). That's a terrible complexity.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Super easy way to shuffle an array.