How often do I need to seed SRAND? And another question

In the following loop, how often do I need to seed srand to ensure I get a different random number for my trapX and Y variables?

1
2
3
4
5
6
7
8
9
for (int i = 0; i < numTraps; i++) {
	srand (time ( NULL ) );
	int trapY = rand() % (board.size()-1);
	srand (time ( NULL ) );
	int trapX = rand() % (board[0].size()-1);
	while (board[trapY][trapX] != '*') {
		trapY = rand() % (board.size()-1);
		trapX = rand() % (board[0].size()-1);
}


Also, board is a multidimensional vector variable defined as private in the class I'm working in. I tried to set up the inner loop as a do-while, but the compiler gave me a size limit exception. I initialize the size of board as [7][10] in the constructor. Here's what I tried:
1
2
3
4
5
6
7
for (int i = 0; i < numTraps; i++) {
int trapY, trapX;	
srand (time ( NULL ) );
do {
  trapY = rand() % (board.size()-1);
  trapX = rand() % (board[0].size()-1);
} while (board[trapY][trapX] != '*');

Exactly zero times. You call it once at the beginning of the program.
Calling srand in the loop ensures that you always get the same number (within one second).
Thanks Athar. Is it a general practice to call it in main(), or would it be more OO to call it in an initializer class constructor (if only one instance of the object would be created?)
Call it once in main(). Using a class for this would be abuse of OO.
It would be one thing to have a PRN generator class that allows you to generate multiple independent sequences of numbers, but if you use srand and rand, you'll always have one shared state which defeats the purpose.
Topic archived. No new replies allowed.