由于这是一个令人敬畏的意外特征,它使得"洗牌"一系列"卡片"变得糟糕.我得到相同数字的事实告诉我,每次采摘单独的种子时我都遇到了一些问题.我使用srand48或time(NULL)拨打电话不正确吗?我缺少一些潜在的逻辑漏洞吗?在迭代之间没有足够的时间来使值time()不同吗?
代码正在Linux上运行.
void shuffle()
{
int i_rnd; /* Integer random number, range 0..100 */
int i_rnd2;
card tempCard; /*temporary card to facillitate swapping*/
int i = 0; /*can't use a FOR loop 'cause we're not using c99 standard*/
while(i < 1000)
{
srand48( (unsigned) time( NULL ) ); /* Seed the random number generator */
i_rnd = (int) ( drand48() * 100);
i_rnd = i_rnd%52; // return a random number 0-51
i_rnd2 = (int) ( drand48() * 100);
i_rnd2 = i_rnd2%52; // return a random number 0-51
/*we have two random numbers, now exchange the two objects with the
/ picked array indices */
tempCard = cardDeck[i_rnd];
cardDeck[i_rnd]=cardDeck[i_rnd2];
cardDeck[i_rnd2]=tempCard;
//swap complete. increment counter so we can eventually get out of the while
i++;
}
return;
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*lis 14
您需要为伪随机数生成器播种一次,而不是每次使用它.
在给定某个种子值的情况下,许多(大多数?)伪随机数生成器(PRNG)是确定性的.如果time()每次循环执行时返回相同的值,则每次使用PRNG时都会使用相同的值,因此当您查询它以获取随机数时,它将返回相同的值.