How to check repetition of numbers in an array?

穿精又带淫゛_ 提交于 2019-12-13 05:46:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!