i want to use arc4random but produced Numbers are must different each other.
How do i do this example?
i want to use arc4random but produced Numbers are must different each other.
How do i do this example?
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
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)
}
}
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"