Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Last active December 24, 2018 21:55
Show Gist options
  • Save ijoshsmith/5e3c7d8c2099a3fe8dc3 to your computer and use it in GitHub Desktop.
Save ijoshsmith/5e3c7d8c2099a3fe8dc3 to your computer and use it in GitHub Desktop.
Randomly shuffle a Swift array
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)")
@Maxnelson997
Copy link

why organisms? hahaha. Thanks tho!

@jakerockland
Copy link

jakerockland commented Sep 7, 2017

@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() }
        }
    }
}

@husaynhakeem
Copy link

husaynhakeem commented Jan 28, 2018

Or this:

extension Array {
    mutating func shuffle() {
        for _ in indices {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

@alimir1
Copy link

alimir1 commented Aug 25, 2018

@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