【发布时间】:2011-02-04 01:34:57
【问题描述】:
尽管这是一个非常棒的意外功能,但它却是一种糟糕的方式来“洗牌”一系列“卡片”。我得到相同数字的事实告诉我,我每次采摘不同的种子时都遇到了一些问题。我是否不正确地使用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;
}
【问题讨论】:
-
42 是生命、宇宙和一切的答案。
-
该程序会为您提供 答案,而无需执行不必要的步骤。我希望我有一台像你这样的电脑。
-
@Mike 你把我打败了!
-
@Andrew Cooper 让我们说......“一个人必须走多少条路?”并称之为千年。