Produced Numbers are must different each other with arc4random

67 Views Asked by At

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

How do i do this example?

3

There are 3 best solutions below

5
Duncan C On BEST ANSWER

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)
    }
}
7
Xcoder On

You can use Set to easily achieve this:

var randomSet: Set<Int> = [] //Sets guarantee uniqueness
var array: [Int] = [] //Use arrays to guarantee the order
while randomSet.count < 2 {
    randomSet.insert(Int(arc4random())) //Whatever random number generator you use
}
for number in randomSet {
    array.append(number)
}
//Now you can use the array for your operations
0
Leo Dabus On

You can use a set to check if the random number was inserted appending the member after checking if it was inserted:

var set: Set<Int> = []
var randomElements: [Int] = []
let numberOfElements = 10
while set.count < numberOfElements {
    let random = Int(arc4random_uniform(10))  //  0...9
    set.insert(random).inserted ? randomElements.append(random) : ()
}
print(randomElements) // "[5, 2, 8, 0, 7, 1, 4, 3, 6, 9]\n"