问题
Even though , I execute the below code again & again I get the same Output. But , I think it should not:
int ObjectCount =500;
NSMutableArray *mut_arr = [[NSMutableArray alloc]initWithCapacity:0];
for (int i = 0; i<ObjectCount ; i++)
{
[mut_arr addObject:[NSNumber numberWithInt: rand()%ObjectCount]];
}
NSSet* uniqueSet = [NSSet setWithArray:mut_arr];
NSLog(@"Array of %d objects generates %d Unique Objects",[mut_arr count],[uniqueSet count]);
The output is as follows:
Array of 500 objects generates 317 Unique Objects
Here, Since the array contains random numbers the unique set count should be same again & again for same ObjectCount.
回答1:
You're not actually generating unique NSNumber
objects; some of them are equal.
A NSArray
can contain multiple objects that are equal. A NSSet
can not. This is why the set created from your array has less objects.
The reason why you're always getting 317 objects is that you're using rand()
without seeding: Why do I always get the same sequence of random numbers with rand()?
Consider using arc4random()
instead, which is seeding automatically.
回答2:
Use like this
[mut_arr addObject:[NSNumber numberWithInt:(arc4random() % (ObjectCount-1) + 1)]];
来源:https://stackoverflow.com/questions/20096836/why-rand-always-generates-random-numbers-with-fixed-unique-group-count