0

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.

Dani Kemper
  • 343
  • 2
  • 10
  • 1
    Create an array with values from 1 to 30, let's call it `randomArray`. Then `let randomIndex = arc4random_uniform(randomArray.count); let randomValue = randomArray[randomIndex]; randomArray.remove(at:randomIndex)` – Larme Jun 30 '18 at 17:16

2 Answers2

4

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

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
0

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

  • Roger Lindsjö also brings up a good point of using the shuffle method. I think that might be a more simple solution. – Arnav Kaushik Jun 30 '18 at 16:34
  • Thank you for your reaction! The questions keeps coming back. If I print the array it will give me "[ ]" back. So I think the numbers that are generated are not saved in the array. – Dani Kemper Jun 30 '18 at 16:53
  • Interesting. Can you explain how/where you have created the array in the program? – Arnav Kaushik Jun 30 '18 at 19:46