Search code examples
c++randomsrand

Trouble generating random numbers in c++ on a Mac using Xcode


I am writing a program that uses random numbers extensively in different ways and I am getting the same random numbers each time. I know to put srand(time(NULL));at the beginning of the program to seed the random number generator and so I have that, but it isn't working. Perhaps it has something to do with XCode or the Mac or something else? I can't find a similar problem online that I has a solution I haven't already tried. Some ways I'm using the random numbers are:

for (int i=0; i<num; i++)
{
    chrom_arr[i] = i;
}
random_shuffle(&chrom_arr[0], &chrom_arr[num-1]);

(to get an array with a series of random ints between 0 and num-1)

int crossover = rand() % num;

and other simple things like that. Even though I have srand(time(NULL)); at the beginning, it still doesn't work. I've also tried srand(time(0)); and also putting it in different parts of the program, but I have since learned that's not right.


Solution

  • You should try somethig like this:

    srand(static_cast<unsigned int>(time(0)));
    std::shuffle(chrom_arr.begin(), chrom_arr.end(), default_random_engine(rand()));
    

    This will work as long as chrom_arr is a std::vector. Once you are using C++, I presume this is what you are trying to do.