Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Last active December 24, 2018 21:55
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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)")
@qb20nh
Copy link

qb20nh commented Dec 22, 2015

Is it uniform?

@thuutien
Copy link

thanks

@lucasacw
Copy link

Thanks! Super easy way to shuffle an array.

@ZhipingYang
Copy link

ZhipingYang commented Mar 6, 2017

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

@LouisDotCom
Copy link

Quite helpful! Thanks!

@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