1

I want to generate a random number between 1 and 10. When the user clicks on the “next” button then a random question must be printed and questions can not repeat. The problem is that sometimes the question is repeating. Can anyone help me or give some reference or tutorial?

- (IBAction)nextQuestion:(id)sender
{
    NSInteger randomNum = arc4random() %10 ;
    int countCounter= counter++;
    [self.btnNext setTitle:@"Next" forState:UIControlStateNormal];

    if(countCounter==4)
    {
        self.btnNext.hidden=YES;
        self.btnQuizDone.hidden=NO;
    }

    switch ( arc4random()%10) 
    {
      case 0:
      {
          NSLog(@"zero");

          [lblQuestion setText:@"Q10:question number ten"];

      }
      break;
     case 1:
      {
          NSLog(@"one");
          [lblQuestion setText:@"Q2:question number two"];

      }
      break;
      case 2:
      {
          NSLog(@"two");
          [lblQuestion setText:@"Q6:question number six"];

      }
      break;
      case 3:
      {
          NSLog(@"three");
          [lblQuestion setText:@"Q5:question  number five"];

      }
       break;
      case 4:
      {
          NSLog(@"four");
          [lblQuestion setText:@"Q3:question number three"];

      }
      break;
      case 5:
      {
          NSLog(@"five");
          [lblQuestion setText:@"Q9:question  number nine"];

      }
      break;
      case 6:
      {
          NSLog(@"six");
          [lblQuestion setText:@"Q7:question  number seven"];

      }
      break;
      case 7:
      {
          NSLog(@"seven");
          [lblQuestion setText:@"Q4:question  number four"];


      }
      break;
      case 8:
      {
          NSLog(@"eight");
          [lblQuestion setText:@"Q1:question  number one"];

      }
      break;
      case 9:
      {
          NSLog(@"nine");
          [lblQuestion setText:@"Q8:question  number eight"];

      }
      break;

      default:
          break;
    }
}
  • 1
    You forgot "break;" on case 3 – Paolo Brandoli Sep 18 '12 at 11:58
  • 1
    look at this : http://stackoverflow.com/questions/196017/unique-random-numbers-in-o1 this too: http://stackoverflow.com/questions/1608181/unique-random-numbers-in-an-integer-array-in-the-c-programming-language – Arun Sep 18 '12 at 12:05
  • 1
    You need to remember the already used question numbers, there is no way around this, afaik. – martinstoeckli Sep 18 '12 at 12:06

8 Answers8

6

How about this.

- (IBAction) getNextRandomQues:(id) sender
{
   int randomQuesIndex = (arc4random() % mutableArrayOfQuestions.count) + 1;
   [mutableArrayOfQuestions removeObjectAtIndex: randomQuesIndex];
}

mutableArrayOfQuestions could be array of "Question" (Question could be a class to modal a question) or a simple array of question indexes. Idea is to select the question from mutableArrayOfQuestions randomly and remove it so that next time it will not selected again.

msk
  • 8,885
  • 6
  • 41
  • 72
4

There is a simpler approach to do this.
You can simply create a NSMutableArray of 10 numbers:

NSMutableArray* numbers=[[NSMutableArray alloc]init];
for(int i=0; i<10; i++)
{
    [numbers addObject: [NSNumber numberWithInt: i]];
}

And everytime you need a random number, extract one number randomly from the array, and delete it:

int randomIndex= random()%[numbers size];
NSNumber* randomNumber=[numbers objectAtIndex: randomIndex];
[numbers removeObjectAtIndex: randomIndex];
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
2

What you want is actually a permutation.

Idea 1:

You have N questions. K questions are not used (0 at the beginning) Algorithm:

  1. Generate random number r = arc4random() % (N - K)
  2. Find the r-th not used question.
  3. Register this question as used, decrement K.

Idea 2:

Generate the indices for the questions at the beginning:

Index of questions int indices[] = {0, 1, 2, 3, ..., N}; (generate this from the value of N)

Randomly swap indices - generating a random permutation.

for (int i = 0; i < 10 * N; i++) {
   int pos1 = arc4random() % N;
   int pos2 = arc4random() % N;

   swap(indices, pos1, pos2);
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

Like Sulthan said, but use the Fisher-Yates shuffle algorithm.

int i = N;
while (-- i) {
  int pos1 = arc4random() % (i + 1);
  swap(indices, pos1, i);
}

This algorithm is notorious for people getting it wrong (see http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html). I've had to fix the above twice already, and I'm still not sure it's right! If at all possible, use a random-shuffle algorithm from a library.

Buster
  • 546
  • 7
  • 23
0

In a set of 10 questions you may very well have a question repeated even with random selection. Each question has a 1 in 10 chance to be selected and in a truly random selection, there is a chance that the same question may be selected again. This is because the kind of selection you are doing is one where you select the item from the container and then you put it back.

If a question must not be repeated then what you will need to do is to have some kind of a mechanism so that when a question is used, it is not put back into the set of questions from which the selection is made.

So you will need to modify your code so that you have an array of questions and when one is selected, that question is removed from the random selection the next time that you produce a random question. Then once that random selection is done, you put the removed question back into the set and remove the one just selected.

This means that the first time you select, you will do a 1 in 10 random number. After that it will always be a 1 in 9 random number.

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
0

Do this:

-(NSMutableArray *)randomNumberGenrator:(NSMutableArray *)arrValues{

NSUInteger totalcount = [arrValues count];
for (NSUInteger i = 0; i < totalcount; ++i) 
 {
    // Select a random element between i and end of array to swap with.
    int nElements = totalcount - i;
    int n = (random() % nElements) + i;
    [arrValues exchangeObjectAtIndex:i withObjectAtIndex:n];
 }
 return arrValues;
}
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
0
public int[] a = new int[10]{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

   public int onNextClickGetRandomQuestionNumber()
   {
       int k = arc4random()%10;



       if (!Exists(k,a))
       {
           for (int i = 0; i < a.Length; i++)
           {
               if (a[i] < 0)
               {
                   a[i] = k;
                   return i;
               }
           }

           for (int i = 0; i < a.Length; i++)
           {
               a[i] = -1;
           }
       }
       else
       {
           onNextClickGetRandomQuestionNumber();
       }

       return -1;


   }

    public  bool Exists(int parameter,int[] Massive)
    {
        for (int i = 0; i < Massive.Length; i++)
        {
            if( parameter == Massive[i])
            {
                return true;
            }
        }
        return false;
    }

thats some crappy i generated , i guess the idea is exactly that you need =)

m4ngl3r
  • 552
  • 2
  • 17
0

Follow this code

NSMutableIndexSet *indexSet = [NSMutableIndexSet new];

while ([indexSet count]<10) {

int randomNumber = arc4random_uniform(11);

   if(randomNumber!=0)
   {
       [indexSet addIndex:randomNumber];
   }
}
Romit M.
  • 898
  • 11
  • 28