tags:

views:

78

answers:

4

I understand, using srand(time(0)), helps in setting the random seed. However, the following code, stores the same set of numbers for two different lists.

Wondering, how do I generate the different set of numbers when the following function gets called more than once.

void storeRandomNos(std::list<int>& dataToStore)
{

    int noofElements = 0;
    srand(time(0));


    noofElements = (rand() % 14 ) + 1;

    while ( noofElements --)
    {
        dataToStore.push_back(rand() % 20 + 1 );
    }
}

Here is the rest of the code.

void printList(const std::list<int>& dataElements, const char* msg);
void storeRandomNos(std::list<int>& dataToStore);
int main()
{
    std::list<int> numberColl1;
    std::list<int> numberColl2;


    storeRandomNos(numberColl1);
    storeRandomNos(numberColl2);

    printList(numberColl1 , "List1");
    printList(numberColl2 , "Second list");


}


void printList(const std::list<int>& dataElements, const char* msg)
{

    std::cout << msg << std::endl;
    std::list<int>::const_iterator curLoc = dataElements.begin();

    for ( ; curLoc != dataElements.end() ; ++curLoc)
    {
        std::cout << *curLoc << ' ';
    }
}
+2  A: 

do the srand(time(0)) once at the beginning of your program.

Alexandre C.
Thanks for the solution.
+6  A: 

Initialize the RNG only once, when the main program starts. Not each time you step into your function. Otherwise, chances are the function is called twice within the same second, which may give you identical results for time(0).

tdammers
Thanks for the solution.
+8  A: 

A pseudo-random generator such as rand(), is simply a mathematical function that takes an input -- the seed -- and does some processing on it. It returns the new value it has produced and also sets that as the new seed. The next time it will use that new seed value.

Because computers are deterministic, every time you call rand() with the same seed, it will produce the same output value. That is why it is pseudo random.

In your example, you used the same seed twice because time(0) returns the time in seconds and your two function calls took place within that same second (because computers are pretty fast).

As the other commenters have said, it's only necessary to seed to a fairly random value (i.e. the current time) once.

Hollance
Thanks for the detailed explanation.
A: 

You need to use srand(time(0)) only once in every thread that calls rand() in your program to get pseudo random numbers.

Donotalo