I need to generate 8 random integers, but they need to be unique, aka not repeated.
For example, I want 8 numbers within the range 1 to 8.
I've seen arc4random but I'm not sure how to make them unique ?
Solution
-(NSMutableArray *)getRandomInts:(int)amount from:(int)fromInt to:(int)toInt {
if ((toInt - fromInt) +1 < amount) {
return nil;
}
NSMutableArray *uniqueNumbers = [[[NSMutableArray alloc] init] autorelease];
int r;
while ([uniqueNumbers count] < amount) {
r = (arc4random() % toInt) + fromInt;
if (![uniqueNumbers containsObject:[NSNumber numberWithInt:r]]) {
[uniqueNumbers addObject:[NSNumber numberWithInt:r]];
}
}
return uniqueNumbers;
}
Here's some psuedo code
allKeys
method)If you want to restrict to numbers less than some threshold M, then you can do this by:
If M=8, or even if M is close to 8 (e.g. 9 or 10), then this takes a while and you can be more clever.
Checking for already generated numbers is potentially expensive (theoretically, it could take forever.) However, this is a solved problem. You want a shuffling algorithm, like the Fisher-Yates_shuffle
On iOS probably something like:
Try this code...this will give you all the possible unique number set in Mutable array...
Don't forget to add this method :)
Store the numbers in an array, and each time you generate the next - check if it already exists in the array. If not, then add it and continue.
Uniqueness is something that you need to provide-- randomness APIs won't do this for you.
As has been suggested, you can generate a number and then check to see whether it collides with something you've already generated, and if so, try agin. Please note however, that depending on the quantity of numbers and the size of the range, this becomes an algorithm that doesn't have a guaranteed end point.
If you're really just trying to get a contiguous set of numbers in random order, this is a not the way to do it, since it could take an unpredictably long time to complete. In this case, building an array of all desired values first, and then "shuffling" the array is a better choice. The best shuffle is the Fisher-Yates, but if you don't need it to be perfectly unbiased, you could also do what's described here.