Generating random numbers in Objective-C -
i'm java head mainly, , want way generate pseudo-random number between 0 , 74. in java use method:
random.nextint(74)
i'm not interested in discussion seeds or true randomness, how accomplish same task in objective-c. i've scoured google, , there seems lots of different , conflicting bits of information.
you should use arc4random_uniform() function. uses superior algorithm rand. don't need set seed.
#include <stdlib.h> // ... // ... int r = arc4random_uniform(74);
the arc4random man page:
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 arc4random() function uses key stream generator employed arc4 cipher, uses 8*8 8 bit s-boxes. s-boxes can in (2**1700) states. arc4random() function returns pseudo- random numbers in range of 0 (2**32)-1, , therefore has twice range of rand(3) , random(3). arc4random_stir() function reads data /dev/urandom , uses permute s-boxes via arc4random_addrandom(). there no need call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself. examples following produces drop-in replacement traditional rand() , random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)rand_max + 1))
Comments
Post a Comment