How do I shuffle an array in Swift?

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

    This is how to shuffle one array with a seed in Swift 3.0.

    extension MutableCollection where Indices.Iterator.Element == Index {
        mutating func shuffle() {
            let c = count
            guard c > 1 else { return }
    
    
            for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
                srand48(seedNumber)
                let number:Int = numericCast(unshuffledCount)
                let r = floor(drand48() * Double(number))
    
                let d: IndexDistance = numericCast(Int(r))
                guard d != 0 else { continue }
                let i = index(firstUnshuffled, offsetBy: d)
                swap(&self[firstUnshuffled], &self[i])
            }
        }
    }
    

提交回复
热议问题