为什么Rand()总是生成具有固定唯一组计数的随机数? [英] Why Rand() always generates random numbers with fixed Unique Group count?
问题描述
尽管如此,我还是再次执行以下代码&再次,我得到相同的输出.但是,我认为不应该:
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]);
输出如下:
由500个对象组成的数组会生成317个唯一对象
Array of 500 objects generates 317 Unique Objects
在这里,由于数组包含随机数,因此唯一集计数应再次相同&再次使用相同的ObjectCount.
Here, Since the array contains random numbers the unique set count should be same again & again for same ObjectCount.
推荐答案
您实际上并没有生成唯一的NSNumber
对象.其中一些是平等的.
You're not actually generating unique NSNumber
objects; some of them are equal.
NSArray
可以包含多个相等的对象. NSSet
不能.这就是从数组创建的对象较少的原因.
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.
总是获得317个对象的原因是您使用的是rand()
而没有种子:
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()?
考虑改用arc4random()
,它会自动播种.
Consider using arc4random()
instead, which is seeding automatically.
这篇关于为什么Rand()总是生成具有固定唯一组计数的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!