Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
218 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...