Search code examples
iosobjective-carc4random

Using arc4random function to produce unique values


I am creating a quiz app for the iPhone. Currently my questions are being selected randomly with the arc4random function.

The problem is that I want each question to be displayed only once. Is there a way that I make the arc4random function generate unique numbers and then stop once it has generated all possible numbers?

This is what i am currently using to generate my random number:

QuestionSelected = arc4random() %4;

Any help would be great.


Solution

  • NSMutableArray *questions=[NSMutableArray new];
    //creating an array to save questions
    // Place in viewDidLoad
    for(;;) {
        //randomly select question
        QuestionSelected = arc4random() % 4;
        //check if question contains this number
        //if it does - continue looping
        if(![questions containsObject:@(QuestionSelected)]){
            //so it doesn't - we add this number to array
            [questions addObject:@(QuestionSelected)];
            break;
            //and exit loop
        }
    
     }
    

    Thats all