I'm trying to generate up to 5 numbers between 0-4 and doesn't re generate the same number more than once. The program will stop after three attempts, therefore the random numbers generated should read 4,3,2 and not 4,3,4(For example).
I've created an array with 5 string elements in it. at least 3 of the strings in the array will be displayed on a label when the button is clicked 3 times. After the button is clicked 3 times, the app will come to an end. However, the issue is that some of the strings in the array keeps repeating itself each time the button is clicked. I found a method that prevents the number from repeating (1,3,1) instead of (1,1,3) for eg. But in my case i do not want a number to be generated once it was already generated. For eg. (1,3,4) instead of (1,3,1) where the (1) is re-generated.
var fruits: [String] = ["Apple", "Mango", "Cherry", "Strawberry", "Blueberry", "Banana"] // fruits to be displayed in the label
func randomizeNum() -> UInt32 {
var randomNumber = arc4random_uniform(UInt32(fruits.count))
while previousNumber == randomNumber {
randomNumber = arc4random_uniform(UInt32(fruits.count))
}
displayLbl.text = fruits[Int(randomNumber)]
previousNumber = randomNumber
print("the random num is \(randomNumber)") // This prints for example 5, 1, 5. Need it to print only numbers that's not yet displayed with 3 attempts.
return randomNumber
}
I expect the output of this function to generate a random number like 0,4,1 but it generates 5,1,5 or 0,4,0 where the (0) is re-generated again.
Aucun commentaire:
Enregistrer un commentaire