random BOOLs in an efficient way for cocos2d
-
26-04-2021 - |
Question
According to Steffen's post this is an efficient way to generate random BOOL
s in cocos2d
+(BOOL) getYesOrNo
{
return (CCRANDOM_0_1() < 0.5f);
}
but how do I set a range for this? (e.g. 0 - 29 is the interval and 5 ones BOOL
=
NO
, 25 ones BOOL
=
YES
)
Solution
you can do something like this:
+(BOOL) getYesOrNo
{
int tmp = (arc4random() % 30)+1;
if(tmp % 5 == 0)
return YES;
return NO;
}
OTHER TIPS
You should use arc4random
for random number generator.
#include <stdlib.h>
u_int32_t
arc4random(void);
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 and random.
-(BOOL)foo4random
{
u_int32_t randomNumber = (arc4random() % ((unsigned)RAND_MAX + 1));
if(randomNumber % 5 ==0)
return YES;
return NO;
}
For more information on arc4random
type
man arc4random
on terminal.
The following code will generate a random bool value:
-(BOOL) randomBool
{
int tmp = (arc4random() % 10);
if(tmp % 2 == 0)
return YES;
return NO;
}