Swift store all numbers that are random generated and won't generated them again

74 Views Asked by At

I am trying to store all numbers that the random number generator generate. After that the number generator needs to check if the number already was generated and if so it will keep generate a new number until all number for example 1 to 30 are generated. I have so far only the random number generator:

if let Aantalvragen = snapshot?.data()!["Aantal vragen"] as? String {
       self.AantalVragenDef = Aantalvragen
}
let RandomVraag = Int(arc4random_uniform(UInt32(self.AantalVragenDef)!) + 1)

AantalVragenDef is an number that indicates how many questions there are. So the generator knows how far it can generate. Please help.

2

There are 2 best solutions below

0
Roger Lindsjö On

The easiest is probably to create an array or list and fill it with the numbers 1 to n that you want, shuffle it and then use the numbers in the order they appear. That way you are guaranteed that each number show up exactly once.

See how to shuffle an array in Swift

3
Arnav Kaushik On

I believe what you are trying to get is a random generator that generates numbers from 1 to the number of questions, but if the number already exists, you don't want to keep it. I suggest using if-else statements and arrays.

The code might look something like this:

if let Aantalvragen = snapshot?.data()!["Aantal vragen"] as? String {
   self.AantalVragenDef = Aantalvragen
}

var array = [Int]()

while array.count != self.AantalVragenDef {
    let RandomVraag = Int(arc4random_uniform(UInt32(self.AantalVragenDef)!) + 1)
    if array.contains(RandomVraag) == false {
        array.append(RandomVraag)
    }

}

This loop will continue until there are (number of questions) integers in the array. Let me know if this is what you are looking for.

Good Luck, Arnav