Avoiding Repeated seed generation using srand()

2019-03-06 15:21发布

I have a typical situation where I need to generate a batch of random numbers. I have used a loop which generates 100 random numbers on each pass:

for(int i=0; i<npasses; i++)
{
   srand(time(NULL)); //Initialize seed

   for(int j=0; j<100; j++)
      printf("%d ", rand()%10);

   printf("\n"); //New line after 100 numbers
}

Now, the inner loop executes in less than a millisecond. As a result, there is no change in the value of time(). This re-initializes the seed (srand()) to the same value and my random numbers are REPEATED..

Can anyone suggest a workaround/fix.

4条回答
干净又极端
2楼-- · 2019-03-06 15:52

Keep srand out:

srand(time(NULL)); //Initialize seed
for(int i=0; i<npasses; i++)
{
   for(int j=0; j<100; j++)
      printf("%d ", rand()%10);

   printf("\n"); //New line after 100 numbers
}
查看更多
叼着烟拽天下
3楼-- · 2019-03-06 15:58

Set the seed once, before the loop.

查看更多
三岁会撩人
4楼-- · 2019-03-06 16:00

try this

srand(clock()); //Initialize seed
查看更多
别忘想泡老子
5楼-- · 2019-03-06 16:01

You can use the random generator to generate a new seed.

For example:

srand((unsigned int)rand());

And use srand(time(NULL)) only once before the loop. But as suggested in another answer, you might as well drop the whole srand inside the loop as well.

查看更多
登录 后发表回答