How do I shuffle an array in Swift?

前端 未结 25 2182
长发绾君心
长发绾君心 2020-11-21 05:44

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in o

相关标签:
25条回答
  • 2020-11-21 06:36

    In SWIFT 4

    func createShuffledSequenceOfNumbers(max:UInt)->[UInt] {
    
        var array:[UInt]! = []
        var myArray:[UInt]! = []
        for i in 1...max {
            myArray.append(i)
        }
        for i in 1...max {
            array.append(i)
        }
        var tempArray:[Int]! = []
        for index in 0...(myArray.count - 1) {
    
            var isNotFinded:Bool = true
            while(isNotFinded){
    
                let randomNumber = arc4random_uniform(UInt32(myArray.count))
                let randomIndex = Int(randomNumber)
    
                if(!tempArray.contains(randomIndex)){
                    tempArray.append(randomIndex)
    
                    array[randomIndex] = myArray[index]
                    isNotFinded = false
                }
            }
        }
    
        return array
    }
    
    0 讨论(0)
  • 2020-11-21 06:37

    Swift 3 solution, following @Nate Cook answer: (work if the index starts with 0, see comments below)

    extension Collection {
        /// Return a copy of `self` with its elements shuffled
        func shuffle() -> [Generator.Element] {
            var list = Array(self)
            list.shuffleInPlace()
            return list
        } }
    
    extension MutableCollection where Index == Int {
        /// Shuffle the elements of `self` in-place.
        mutating func shuffleInPlace() {
            // empty and single-element collections don't shuffle
            if count < 2 { return }
            let countInt = count as! Int
    
        for i in 0..<countInt - 1 {
            let j = Int(arc4random_uniform(UInt32(countInt - i))) + i
                guard i != j else { continue }
                swap(&self[i], &self[j])
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:40

    Here's some code that runs in playground. You won't need to import Darwin in an actual Xcode project.

    import darwin
    
    var a = [1,2,3,4,5,6,7]
    
    func shuffle<ItemType>(item1: ItemType, item2: ItemType) -> Bool {
        return drand48() > 0.5
    }
    
    sort(a, shuffle)
    
    println(a)
    
    0 讨论(0)
  • 2020-11-21 06:42

    Here's something possibly a little shorter:

    sorted(a) {_, _ in arc4random() % 2 == 0}
    
    0 讨论(0)
  • 2020-11-21 06:44

    In Swift 4.2, there is now a method for both a mutable shuffle and immutable shuffled. You can read more about the random generation and array stuff here.

    0 讨论(0)
  • 2020-11-21 06:46
    let shuffl = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: arrayObject)
    
    0 讨论(0)
提交回复
热议问题