我一直在做一些休闲假期计算。我的小项目是模拟意大利的“tomboli”游戏。一个关键的组成部分是对以下过程的模拟;
游戏由一个人控制,他拿着一袋90颗弹珠,编号从1到90。他从袋子里随机抽出一颗弹珠,每次向玩家喊出弹珠编号。
经过一番思考,我为这个构建块编写了以下代码;
// NBR marbles, numbered 1...NBR are in a bag. Simulate randomly
// pulling them from the bag, one by one, until the bag is empty
void bag( int random_sequence[NBR] )
{
int i;
// Store each marble as it is pulled out
int *store = random_sequence;
// Array of marbles still in the bag
int not_yet_pulled[NBR];
for( i=0; i<NBR; i++ )
not_yet_pulled[i] = i+1; // eg NBR=90; 1,2,3 ... 90
// Loop pulling marbles from the bag, one each time through
for( i=NBR; i>=1; i-- )
{
int x = rand();
int idx = x%i; // eg i=90 idx is random in range 0..89
// eg i=89 idx is random in range 0..88
// ...
// eg i=1 idx is random in range 0..0
// (so we could optimize when i=1 but not worth the bother)
*store++ = not_yet_pulled[idx];
// Replace the marble just drawn (so it cannot be pulled again)
// with the last marble in the bag. So;
// 1) there is now one less marble in the bag
// 2) only marbles not yet pulled are still in the bag
// If we happened to pull the last marble in the *current subarray*, this is
// not required but does no harm.
not_yet_pulled[idx] = not_yet_pulled[i-1];
}
}
我知道在随机数的游戏模拟中到处都是微妙之处和陷阱,所以虽然我对我的代码很满意,但我的信心还不到 100%。所以我的问题是;
1)我的代码有什么问题吗?
2) [如果 1) 的答案是否定的] 我是否在不知不觉中使用了标准洗牌算法?
3) [如果 2) 的答案是否定的] 我的算法与标准替代方案相比如何?
编辑 感谢所有回答的人。我将接受 Aidan Cully 的回答,因为事实证明我正在重新发现 Fisher-Yates 算法,并揭示了问题的核心。当然,我可以通过预先进行一些研究来节省自己的时间和精力,这并不奇怪。但另一方面,这是一个有趣的爱好项目。其余的模拟都是例行公事,这是最有趣的部分,如果我自己不去,我会剥夺自己的乐趣。此外,我试图模拟一个人从袋子里取出弹珠,但在我意识到这种情况与洗牌完全相似的时候已经很晚了。
另一个有趣的地方是有一个小缺陷,由 Ken 指出,经常重复的模式 rand()%N 并不是从 0..N-1 范围内选择随机数的好方法。
最后,我的Fisher-Yates 版本缺乏优雅的技巧,它允许就地改组的良好特性。结果,我的算法会以同样随机但反向的洗牌告终。