dimanche 13 janvier 2019

Generate random number not in array in swift

So, I want to generate a random number that is not in the array. If it is, then it will keep generating until it generate a number that is not. Then, it will append that number to the array.

After the first time. It doesn't work. The first time always work since the array is empty. I think there is something wrong with my while loop.

Here is my code:

 var selectQuestion: UInt32 = 0

var questionsArray:[UInt32] = []

var questionNotAsked = false

if (questionsArray.isEmpty == true) {
            questionNotAsked = true
            selectQuestion = arc4random_uniform(10)
        }

        while(!questionNotAsked) {
            selectQuestion = arc4random_uniform(10) //0-9
            for questions in self.questionsArray {
                if selectQuestion == questions {
                    self.questionNotAsked = false
                    return
                } else {
                    self.questionNotAsked = true
                }
            }
        }




Aucun commentaire:

Enregistrer un commentaire