Generating New Outputs in Rand()

Hey guys,
I am having a problem with the rand() function. The first time I execute the program, the random values come, but every time after that, the random values which are generated are the same. Here is my code :

1
2
3
4
5
for(z = 1; z <= 6; z++)
     {
     BallResult[z] = rand() % 10000 + 1;
     cout << BallResult[z] << endl;
     }


Here is my current output set which keeps on coming every time.

42
8468
6335
6501
9170
5725


Can anyone help me out with this ??

Cheers
Tejas
You need to seed your random number generator. It's a simple algorithm so if you don't give it different values it will never really change.

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
The problem with srand( time (NULL)) is that the values returned are within touching distance of each other. For e.g., here are outputs when I ran the program four times

6201
6209
6212
6217


These values are not random enough. Another problem is that when I put in a for loop, the same values are returned each time.

1
2
3
4
5
6
for(z = 1; z <=6; z++)
     {
           srand (time(NULL));
     BallResult[z] = rand() % 10000 + 1;
     cout << BallResult[z] << endl;
      }


With the output something like,

6158
6158
6158
6158
6158
6158


Seed it once and only once. Then do your for loop.
Another problem is that when I put in a for loop, the same values are returned each time.

Note that seeding the random number generator with the same number will generate the same stream of pseudo-random numbers. Placing the call to srand in the loop like that reseeds it, but since it's been so short since the last call, likely time(NULL) is returning the same result as before, hence the same pseudo-random number. Try placing srand (time(NULL)); outside the loop (and call it only once).
Thanks a lot firedraco !!! It's working now. Really appreciate the help. Thanks !!!

Tejas
Topic archived. No new replies allowed.