Why Rand() always generates random numbers with fixed Unique Group count?

我的未来我决定 提交于 2019-12-08 12:00:43

问题


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

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