【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
我主要是Java头,我想要一种生成0到74之间的伪随机数的方法。在Java中我会使用这个方法:
Random.nextInt(74)
我对种子或真正的随机性的讨论不感兴趣,只是你如何在Objective-C中完成相同的任务。 我搜索谷歌,似乎有很多不同的和相互矛盾的信息。
#1楼
最好使用arc4random_uniform
。 但是,这不适用于iOS 4.3。 幸运的是,iOS将在运行时绑定此符号,而不是在编译时绑定(因此不要使用#if预处理器指令来检查它是否可用)。
确定arc4random_uniform
是否可用的最佳方法是执行以下操作:
#include <stdlib.h>
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (74);
else
r = (arc4random() % 74);
#2楼
和C一样,你会这样做
#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;
(假设您的意思是包含0但不包括74,这是您的Java示例所做的)
编辑:随意替换rand()
random()
或arc4random()
rand()
正如其他人指出的那样,非常糟糕)。
#3楼
根据rand(3)的手册页,rand系列函数已被随机淘汰(3)。 这是因为rand()的低12位经历了循环模式。 要获得一个随机数,只需通过使用无符号种子调用srandom()来生成生成器,然后调用random()。 所以,相当于上面的代码
#import <stdlib.h>
#import <time.h>
srandom(time(NULL));
random() % 74;
您只需要在程序中调用一次srandom(),除非您想要更改种子。 虽然你说你不想讨论真正的随机数值,但是rand()是一个非常糟糕的随机数生成器,而random()仍然存在模偏差,因为它会产生0到RAND_MAX之间的数字。 因此,例如,如果RAND_MAX为3,并且您想要一个介于0和2之间的随机数,则获得0的可能性是1或2的两倍。
#4楼
您应该使用arc4random_uniform()
函数。 它使用优越的算法来rand
。 你甚至不需要设置种子。
#include <stdlib.h>
// ...
// ...
int r = arc4random_uniform(74);
arc4random
手册页:
NAME arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdlib.h> u_int32_t arc4random(void); void arc4random_stir(void); void arc4random_addrandom(unsigned char *dat, int datlen); DESCRIPTION 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 (2**1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3). The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom(). There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself. EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
#5楼
我想我可以添加一个我在许多项目中使用的方法。
- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
return (NSInteger)(min + arc4random_uniform(max - min + 1));
}
如果我最终在许多文件中使用它,我通常会将宏声明为
#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))
例如
NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74
注意:仅适用于iOS 4.3 / OS X v10.7(Lion)及更高版本
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3145853