How do I shuffle an array in Swift?

前端 未结 25 2193
长发绾君心
长发绾君心 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:29

    If you want to use simple Swift For loop function use this ->

    var arrayItems = ["A1", "B2", "C3", "D4", "E5", "F6", "G7", "H8", "X9", "Y10", "Z11"]
    var shuffledArray = [String]()
    
    for i in 0..<arrayItems.count
    {
        let randomObject = Int(arc4random_uniform(UInt32(items.count)))
    
        shuffledArray.append(items[randomObject])
    
        items.remove(at: randomObject)
    }
    
    print(shuffledArray)
    

    Swift Array suffle using extension ->

    extension Array {
        // Order Randomize
        mutating func shuffle() {
            for _ in 0..<count {
                sort { (_,_) in arc4random() < arc4random() }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:30

    Simple Example:

    extension Array {
        mutating func shuffled() {
            for _ in self {
                // generate random indexes that will be swapped
                var (a, b) = (Int(arc4random_uniform(UInt32(self.count - 1))), Int(arc4random_uniform(UInt32(self.count - 1))))
                if a == b { // if the same indexes are generated swap the first and last
                    a = 0
                    b = self.count - 1
                }
                swap(&self[a], &self[b])
            }
        }
    }
    
    var array = [1,2,3,4,5,6,7,8,9,10]
    array.shuffled()
    print(array) // [9, 8, 3, 5, 7, 6, 4, 2, 1, 10]
    
    0 讨论(0)
  • 2020-11-21 06:33

    Swift 4 Shuffle the elements of an array in a for loop where i is the mixing ratio

    var cards = [Int]() //Some Array
    let i = 4 // is the mixing ratio
    func shuffleCards() {
        for _ in 0 ..< cards.count * i {
            let card = cards.remove(at: Int(arc4random_uniform(UInt32(cards.count))))
            cards.insert(card, at: Int(arc4random_uniform(UInt32(cards.count))))
        }
    }
    

    Or with extension Int

    func shuffleCards() {
        for _ in 0 ..< cards.count * i {
            let card = cards.remove(at: cards.count.arc4random)
            cards.insert(card, at: cards.count.arc4random)
        }
    }
    extension Int {
        var arc4random: Int {
            if self > 0 {
                print("Arc for random positiv self \(Int(arc4random_uniform(UInt32(self))))")
            return Int(arc4random_uniform(UInt32(self)))
            } else if self < 0 {
                print("Arc for random negotiv self \(-Int(arc4random_uniform(UInt32(abs(self)))))")
                return -Int(arc4random_uniform(UInt32(abs(self))))
            } else {
                print("Arc for random equal 0")
                return 0
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:33

    You can use generic swap function as well and implement mentioned Fisher-Yates:

    for idx in 0..<arr.count {
      let rnd = Int(arc4random_uniform(UInt32(idx)))
      if rnd != idx {
        swap(&arr[idx], &arr[rnd])
      }
    }
    

    or less verbose:

    for idx in 0..<steps.count {
      swap(&steps[idx], &steps[Int(arc4random_uniform(UInt32(idx)))])
    }
    
    0 讨论(0)
  • 2020-11-21 06:34

    In Swift 2.0, GameplayKit may come to the rescue! (supported by iOS9 or later)

    import GameplayKit
    
    func shuffle() {
        array = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(array)
    }
    
    0 讨论(0)
  • 2020-11-21 06:35

    In my case, I had some problems of swapping objects in Array. Then I scratched my head and went for reinventing the wheel.

    // swift 3.0 ready
    extension Array {
    
        func shuffled() -> [Element] {
            var results = [Element]()
            var indexes = (0 ..< count).map { $0 }
            while indexes.count > 0 {
                let indexOfIndexes = Int(arc4random_uniform(UInt32(indexes.count)))
                let index = indexes[indexOfIndexes]
                results.append(self[index])
                indexes.remove(at: indexOfIndexes)
            }
            return results
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题