Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

objective-c - 在Objective-C中生成随机数(Generating random numbers in Objective-C)

I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

(我主要是Java头,我想要一种生成0到74之间的伪随机数的方法。在Java中我会使用这个方法:)

Random.nextInt(74)

I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C.

(我对种子或真正的随机性的讨论不感兴趣,只是你如何在Objective-C中完成相同的任务。)

I've scoured Google, and there just seems to be lots of different and conflicting bits of information.

(我搜索谷歌,似乎有很多不同的和相互矛盾的信息。)

  ask by rustyshelf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use the arc4random_uniform() function.

(您应该使用arc4random_uniform()函数。)

It uses a superior algorithm to rand .

(它使用优越的算法来rand 。)

You don't even need to set a seed.

(你甚至不需要设置种子。)

#include <stdlib.h>
// ...
// ...
int r = arc4random_uniform(74);

The arc4random man page:

(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)) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...