Generate a Swift array of nonrepeating random numbers

后端 未结 3 1909
猫巷女王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:28

    If you use your method the problem is, that you will create a new random-number each time. So you possibly could have the same random-number 4 times and so your array will only have one element.

    So, if you just want to have an array of numbers from within a specific range of numbers (for example 0-100), in a random order, you can first fill an array with numbers in 'normal' order. For example with for loop etc:

    var min = 1
    var max = 5
    for var i = min; i<= max; i++ {
        temp.append(i)
    }
    

    After that, you can use a shuffle method to shuffle all elements of the array with the shuffle method from this answer:

    func shuffle(var list: C) -> C {
        let count = countElements(list)
        for i in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            swap(&list[i], &list[j])
        }
        return list
    }
    

    Ater that you can do something like that:

    shuffle(temp)        // e.g., [3, 1, 2, 4, 5]
    

提交回复
热议问题