8

According to Steffen's post this is an efficient way to generate random BOOLs 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 )

el.severo
  • 2,202
  • 6
  • 31
  • 62

3 Answers3

13

you can do something like this:

+(BOOL) getYesOrNo
{
    int tmp = (arc4random() % 30)+1;
    if(tmp % 5 == 0)
        return YES;
    return NO;
}
nicoz_88
  • 456
  • 3
  • 9
  • This has modulo bias. – Alexander Aug 23 '16 at 15:52
  • 4
    This solution produces false values more than true values, something like 1:10 for false value and that's because the percentage of making 5,10,15,20,25,30 is like 6/30 which make no sense at all – Ali Omari Jan 22 '17 at 13:41
3

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.

Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
0

The following code will generate a random bool value:

-(BOOL) randomBool
{
    int tmp = (arc4random() % 10);
    if(tmp % 2 == 0)
        return YES;
    return NO;
}
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53