Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active December 25, 2015 01:29
Show Gist options
  • Save Ben-G/6896018 to your computer and use it in GitHub Desktop.
Save Ben-G/6896018 to your computer and use it in GitHub Desktop.
Generates a set of unique random numbers. Useful when you want to pick multiple random elements without duplicates.
- (NSArray *)generate:(int)n randomUniqueNumbersBetween:(int)lowerLimit upperLimit:(int)upperLimit
{
NSMutableArray *randomNumberArray = [NSMutableArray arrayWithCapacity:upperLimit-lowerLimit];
// add all numbers to array
for (int i = lowerLimit; i < upperLimit; i++)
{
[randomNumberArray addObject:@(i)];
}
// shuffle array
for (NSUInteger i = 0; i < [randomNumberArray count]; i++)
{
int j = arc4random_uniform([randomNumberArray count]);
NSNumber *jNumber = randomNumberArray[j];
NSNumber *iNumber = randomNumberArray[i];
randomNumberArray[j] = iNumber;
randomNumberArray[i] = jNumber;
}
return [randomNumberArray subarrayWithRange:NSMakeRange(0,n)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment