Generate a Swift array of nonrepeating random numbers

后端 未结 3 1912
猫巷女王i
猫巷女王i 2021-01-20 01:47

I\'d like to generate multiple different random numbers in Swift. Here is the procedure.

  1. Set up an empty array
  2. Generate a random number
  3. Ch

3条回答
  •  旧巷少年郎
    2021-01-20 02:35

    Below is my suggestion. I like this way since it is short and simple :)

    let totalCount: Int = 150 //Any number you asssign
    var randomNumArray: [Int] = []
    var i = 0
    while randomNumArray.count < totalCount {
        i++
        let rand = Int(arc4random_uniform(UInt32(totalCount)))
        for(var ii = 0; ii < totalCount; ii++){
            if randomNumArray.contains(rand){
                print("do nothing")
            } else {
                randomNumArray.append(rand)
            }
        }
    }
    

提交回复
热议问题