Generate random order of series in iphone

Generally, it is required to show something in random order in series such a way that each item must be selected at one time. For example, In a Quiz application, you need to show all questions in random order and each question must be selected and not more than once. For this, use following method:

//Generate random number between 0 to mx-1
-(NSMutableArray *)GenerateRandom: (int)mx
{
 
 NSMutableArray *rand = [[NSMutableArray alloc] initWithCapacity:mx];
 for (int i=0;i<mx;i++)
 {
  NSInteger rnd;
  
  rnd = arc4random() % mx;
  while([rand containsObject:[NSNumber numberWithInt:rnd]])
  {
  rnd = arc4random() % mx;
  }
  
  [rand addObject:[NSNumber numberWithInt:rnd]];
  
 }
 return rand;
}

Suppose you need to call this method for 10 questions:

NSMutableArray *randArray = [self GenerateRandom:10];

Then It will generate array of random number between 0 and 9 and each number will be present in the array in random order.

Hope, It helps.

No comments:

Post a Comment