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 hidden or 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)") | 
@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
  
            
why organisms? hahaha. Thanks tho!