1

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.

Amar
  • 13,202
  • 7
  • 53
  • 71
Sztucki
  • 145
  • 1
  • 12
  • 2
    One solution: Create an array of k elements (with the id of your questions). Then: int index = arc4Randcom()%[theArray count]; You'll get the question with [theArray objectAtIndex:index]. Then, remove the question: [theArray removeObjectAtIndex:index]; – Larme Apr 08 '14 at 13:50
  • What you are looking for is called a "random permutation" or "random shuffle". – Martin R Apr 08 '14 at 13:50
  • Y used Larme approach some time ago – jcesarmobile Apr 08 '14 at 13:51
  • Use the method mentioned by @Larme and `arc4random_uniform([theArray count])`. The reasons for `arc4random_uniform` can be found here:http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c – Robotic Cat Apr 08 '14 at 14:20
  • Was my answer useful? – nicael Apr 09 '14 at 10:29

2 Answers2

2
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

nicael
  • 18,550
  • 13
  • 57
  • 90
1

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

Levi
  • 7,313
  • 2
  • 32
  • 44