3

I am trying to generate a random number between 0 and the size of my array:

    float randomNum = (rand() / RAND_MAX) * [items count];
    NSLog(@"%f",randomNum);
    NSLog(@"%d",[items count]);

randomNum is always 0.0000000

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556

6 Answers6

6

randomNum is always 0.0000000

That's because you're doing integer division instead of floating-point division; (rand() / RAND_MAX) will almost always be 0. (Exercise to the reader: when is it not 0?)

Here's one way to fix that:

float randomNum = ((float)rand() / (float)RAND_MAX) * [items count];

You should also be using arc4random instead.

Community
  • 1
  • 1
Shaggy Frog
  • 27,575
  • 16
  • 91
  • 128
5

Try this instead:

int randomNum = arc4random() % ([items count] +1);

note that randomNum won't do as an array reference. To do that, you want:

int randomRef = arc4random() % [items count];
id myRandomObject = [myArray objectAtIndex:randomRef];

arc4random() returns an u_int32_t (int) which makes it easily transferrable to stuff like dice, arrays, and other real-world problems unlike rand()

Stephen Furlani
  • 6,794
  • 4
  • 31
  • 60
2

If you want it between 0 and your array size it should be:

randomNum = random() % [items count];  // between 0 and arraySize-1


If you want your array size included:

randomNum = random() % ([items count]+1);  // between 0 and arraySize
erkanyildiz
  • 13,044
  • 6
  • 50
  • 73
1

Try rand() * [items count];

IIRC, rand() returns values between 0 and 1.

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
1

people say that arc4random() is the best rnd method...

you can use it this way to get a number in a range:

int fromNumber = 0;
int toNumber = 50;
float randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
NSLog(@"random number is:  %f",randomNumber); // you'll get from 0 to 49

...

int fromNumber = 12;
int toNumber = 101;
float randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
NSLog(@"random number is:  %f",randomNumber); // you'll get from 12 to 100
meronix
  • 6,175
  • 1
  • 23
  • 36
0

Before using rand() you must set a seed, you do so by calling the srand function and passing a seed.

See here for the srand documentation and here for rand.

mmccomb
  • 13,516
  • 5
  • 39
  • 46