问题
I generate random numbers and store them in an array:
int RandomNumber = arc4random() % 12;
[NSMutablearray *Number addObject:[NSNumber numberWithInt:RandomNumber]];
Now I want to make sure the same number is not created randomly again. Can any one please tell me how to do it with sample code.
回答1:
You can use an NSMutableSet
instead of an array while generating the numbers.
The following code will create an array of 10 unique random numbers:
NSMutableSet *aSet = [NSMutableSet setWithCapacity:10];
while([aSet count]<=10){
int Randnum = arc4random() % 12;
[aSet addObject:[NSNumber numberWithInt:Randnum]];
}
NSArray *arrayOfUniqueRandomNumbers = [aSet allObjects];
来源:https://stackoverflow.com/questions/2141121/how-to-check-repetition-of-numbers-in-an-array