Fisher-Yates shuffle 的 C 实现正确吗?
这是 Fisher-Yates 的 C 实现,我想在牌组洗牌例程中使用它。我这样做是否正确(n = 数组长度)?
注意:do-while 循环尝试纠正模偏差(请参阅 在这里)。它会增加程序的一些开销,如果您不关心低位偏差,则可以将其消除。
void shuffle(int *array, int n) {
int i, j, tmp, upper_bound;
srand(time(NULL));
for (i = n - 1; i > 0; i--) {
upper_bound = RAND_MAX - ((RAND_MAX % (i + 1)) + 1);
do {
j = rand() % (i + 1);
} while (j > upper_bound);
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
Here's a C implementation of Fisher-Yates that I want to use in a deck-shuffling routine. Am I doing this correctly (n = length of array)?
Note: The do-while loop attempts to correct for the modulo bias (see here). It adds a bit of overhead to the procedure and could be eliminated if you don't care about the low-bit bias.
void shuffle(int *array, int n) {
int i, j, tmp, upper_bound;
srand(time(NULL));
for (i = n - 1; i > 0; i--) {
upper_bound = RAND_MAX - ((RAND_MAX % (i + 1)) + 1);
do {
j = rand() % (i + 1);
} while (j > upper_bound);
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您应该将用于生成在
0
(包含)和n
(不包含)之间均匀分布的随机数的代码提取到单独的函数中。这是一项很好的工作任务,你在其他地方也需要这样做。其次,我不会在
shuffle
函数内调用srand
,而是依赖调用者来初始化随机数生成器。这样你就可以在一秒钟内多次洗牌。第三,您应该对
j > 进行测试。 upper_bound
,然后除以i + 1
。i
不太可能接近RAND_MAX
。要检查此实现是否正确,您需要确保向随机数生成器询问
log2(n!)
位随机性。换句话说,提供给rand_int
函数的所有n
的乘积必须是n!
。First, you should extract the code for generating a random number that's equally distributed between
0
(inclusive) andn
(exclusive) to a separate function. That's a nice task of work that you will need elsewhere, too.Second, I would not call
srand
inside theshuffle
function but depend on the caller on initializing the random number generator. That way you can shuffle a deck more than once in a second.Third, you should do the test for
j > upper_bound
before dividing byi + 1
. It's unlikely thati
will ever be nearRAND_MAX
.To check whether this implementation may be correct, you need to ensure that you asked the random number generator for
log2(n!)
bits of randomness. In other words, the product of all then
s given to therand_int
function must ben!
.