Search code examples
iosswiftrandomarc4random

Produced Numbers are must different each other with arc4random


i want to use arc4random but produced Numbers are must different each other.

How do i do this example?


Solution

  • How about this:

    let desired = 20
    var randomSet: Set<Int> = [] //Sets guarantee uniqueness
    var array: [Int] = [] //Use arrays to guarantee the order
    
    while array.count < desired {
        let random = Int(arc4random())
        if !randomSet.contains(random) {
            array.append(random)
            randomSet.insert(random)
        }
    }
    

    Or, using LeoDaubus' suggestion:

    while array.count < desired {
        let random = Int(arc4random())
        if randomSet.insert(random).inserted {
            array.append(random)
        }
    }