How to check repetition of numbers in an array?

2019-08-27 23:31发布

问题:

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];