Hi I am trying to create an array from non-repeating random numbers.
I wrote below code numberOfAnimals
which is 10 currently shows how many numbers will be in the array. When I run this in playground I get
"[6, 5, 1, 4, 7, 0]\n" as output of print statement so in total 6 numbers instead of 10. To avoid it I am decreasing value of i
in if
statement in case random number exists in the array already, in this case for loop needs an additional loop to reach 10 but still it does not work.
Can you please check where is the mistake or give me another code suggestion that can work ?
import UIKit
var array = [Int]()
var max : Int = 10
var numberOfAnimals : Int = 10
for var i in 0..<numberOfAnimals {
let randomNumber : Int = Int(arc4random_uniform(UInt32(max)))
if array.contains(randomNumber) {
i = i - 1
} else {
array.append(randomNumber)
}
}
print(array)