views:

197

answers:

5

I am using below code to generate random numbers in range...

int randomNumberWithinRange(int min,int max)
{
        int snowSize = 0;
        do
        {
            snowSize = rand()%max;
        }
        while( snowSize < min || snowSize > max );
        return snowSize;
    }

for(int i = 0; i < 10 ; i++)
  NSlog("@"%d",\t", randomNumberWithinRange(1,100));

If I quit my application and restart, same set of numbers are generated. How to generate different set of random numbers for every launching.

+10  A: 

Do something like for example srand(time(NULL)), i.e. sync it with time (in the initialisation of your program, of course).

phimuemue
As a note, just make this the first line of your application. You only need to call it once.
sharth
+3  A: 

You need to seed the random number generator.

From the man page:

The srand() function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand() is called before any calls to srand() are made, the same sequence shall be generated as when srand() is first called with a seed value of 1.

RC
+3  A: 

You have to initialize the random number generator with a seed as pointed out.

Additionally you should avoid the loop:

int randomNumberWithinRange(int min,int max)
{
  return min + rand() % (max - min + 1);
}
Danvil
A: 

In addition to seeding the random number generator with srand(), your general technique here is not quite right. First of all you should never use modulus for cutting the rand range. This users lower-order bits which are less random. Second, there is no need to loop. You can get the range directly. Here is how to do it:

snowSize = min + (int) (max * (rand() / (RAND_MAX + 1.0)));

frankc
Floats are not necessary here.
Danvil
You are completely wrong. Read the man page for rand.
frankc
No he is not. The random and srandom functions are the ones that have a more random looking low bit sequence. From the man page of random(3): "rand(3) produces a much less random sequence -- in fact the low dozen bits generated by rand go through a cyclic sequence".
JeremyP
Are you talking to me me or him? The example uses rand(3) and therefore should not use % as I said, and you are agreeing with me?
frankc
It only uses the lower-order bits if max is near a power of two. But I think your calculation is more robust.
GregS
+2  A: 

You should consider using arc4random instead of rand, for many reasons, one of which is arc4random doesn't require seeding.

Jasarien