objective-c - 我如何在 Objective-C 中播种 rand() 函数?

标签 objective-c ios c random srand

我正在开发的部分内容是随机公司名称生成器。它从几个名称部分数组中提取。我使用 rand() 函数来绘制随机名称部分。但是,每次启动该应用程序时,总是以相同的顺序生成相同的“随机”数字,因此总是会出现相同的名称。

所以我搜索了 SO,在 C 中有一个 srand() 函数可以用当前时间之类的东西“播种”随机函数,使其更随机 - 比如 srand (时间(NULL))。是否有类似 Objective-C 的东西可以用于 iOS 开发?

最佳答案

为什么不使用不需要种子的arc4random?你可以这样使用它:

int r = arc4random();

Here's一篇将它与 rand() 进行比较的文章。与 rand() 相比,arc4random() 手册页说明了这一点:

The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and random(3).

如果你想要一个范围内的随机数,你可以使用arc4random_uniform()函数。例如,要生成 0 到 10 之间的随机数,您可以这样做:

int i = arc4random_uniform(11);

这是手册页中的一些信息:

arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

关于objective-c - 我如何在 Objective-C 中播种 rand() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12119399/

相关文章:

ios - 强制应用程序在 iPhone 中终止

ios - 如何搜索所有目录? objective-c

ios - 核心数据Fetch请求语法查询

ios - 如何通过 POST 和 AFNetworking 发送变量数据?

iphone - ios - 如何在 ios 中解析 HTML 内容?

c - 结构体中数组的 malloc

c - Sprintf 函数 + 顺序参数

objective-c - 通过弱指针分配给 Block 中的 ivar

objective-c - 寻找一种使用 NSArray 作为一堆按钮的导出的方法

C 程序 - 验证从文本文件中读取的数字