Last active
December 25, 2015 01:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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