macshaggy
macshaggy

Reputation: 367

Seeding Random number generator not working

I have a c++ program that uses a random generator to create a cube. To create the cube I have this:

void generateSquare() {
  int num = 0;
  srand(time(NULL));

  for (int r = 0; r < MSQUARE; r++) {
    for (int c = 0; c < MSQUARE; c++) {
      do {
        num = (rand() % (MSQUARE * MSQUARE)) + 1;
      } while (!checkUnique(num));
      cube[r][c] = num;
    }
  }
}

It only allows a number to be generated one. This function is then wrapped in a do..while loop so that if the square doesn't meet a specific condition a new square will be generated until the one that does meet the condition is generated.

The problem is that it continually is generating the same square over and over again. I thought that the srand(time(NULL)) would seed the rand() function so that it would generate different random numbers each time to create a new unique square every time it is called but it looks like that is not happening.

void checkSquare() {
  do {
    generateSquare();
  } while (!perfect);
}

This is not the actual do...while loop but gives you an idea of how it's being called.

How do I make sure the seed is unique each time?

Upvotes: 1

Views: 2332

Answers (2)

Felipe Centeno
Felipe Centeno

Reputation: 3787

srand sets the seed of the rand function. If you set it to a specific number it will always return you the same sequence of numbers. You will use this if you want to test a program, otherwise you use rand() without srand().

http://www.cplusplus.com/reference/cstdlib/srand/

Upvotes: 0

Kevin
Kevin

Reputation: 7334

You should call srand only once, at the beginning of your program. The reason why your seed is always the same is because time returns a number of seconds. Since you're calling it in a loop it always has the same value (until a second goes by).

Also if you can use C++11 or later you should look at the pseudo-random number generation in the standard library

Upvotes: 3

Related Questions