Mail Archives: djgpp/1998/02/05/19:20:07
> My suggested solution is to grab a value from `time' on
> startup, and
> store it in a static or global variable. On each call
> to randomize,
> increment this variable when using its value; this
> ensures that you
> use a different seed each time. Okay, they're fairly
> predictable, but
> that shouldn't matter too much.
There was just a thread (or two) about this. A couple gurus said that you
should just initialize the function once by calling srand(), if you initialize
it with srand(). I wrote a little program that shows the difference between
seeding once and seeding multiple times. It is set up for a 43-line display.
You hit a key to iterate the loop (if you chose to reseed each time you'll only
see a change if the time has changed.) After hitting lots of keys you can see
that if you call srand() each time it is not random at all.
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define NBR_ROWS 43
#define NBR_COLS 80
int main(void)
{
int theRandNo, rowPosition, colPosition;
char c;
cprintf("Would you like to seed the function\n\r1) At the"
"beginning of the program\n\r");
cprintf("2) At each loop\n\r");
c = getch();
cprintf("Hit lowercase 'x' to exit.\n\r");
if(c != '2')
srand(time(0));
while(getch()!='x'){
if(c == '2')
srand(time(0));
theRandNo = rand();
rowPosition = theRandNo % NBR_ROWS + 1;
colPosition = theRandNo % NBR_COLS + 1;
gotoxy(colPosition, rowPosition);
cprintf("%d, %d", colPosition, rowPosition);
}
return 0;
}
- Raw text -