Question

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.

Was it helpful?

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

OTHER TIPS

You could use an NSMutableArray with the questions, and when a question is selected, remove it from the array. In this case you would generate the random number between 0 and array.count - 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top