我正在为学校作业编写卡片和牌组类(class),而我的洗牌方法并不能始终通过其测试代码。我们应该专门使用在线资源,而不是评分者/讲师的支持,我很快找到了 Fisher Yates 洗牌方法,但我无法理解它的一些细节。我想融入一些我想出的东西,其中一些看起来非常相似。谁能解释我缺少什么以及它的作用吗?这是我的方法:
public void shuffle() {
/**
* I'm trying an orginial idea for the shuffle method of taking the
* element at each index and switching it out with another element
* at a random index
*/
Card placeHolder;
int i;
for (int c = 0; c < cardNum; c++) {
i = (int) (Math.random() * (cardNum-1));
placeHolder = deckList[i];
deckList[i] = deckList[c];
deckList[c] = placeHolder;
}
}
你们真的很接近。我建议更改此设置:
i = (int) (Math.random() * (cardNum-1));
对此:
i = (int) (Math.random() * (cardNum - i) + i);
或者使用ThreadLocalRandom.current().nextInt(origin,bound)
(假设您使用的是1.7或更高版本)。
我是一名优秀的程序员,十分优秀!