gpt4 book ai didi

java - 弥合费舍尔耶茨洗牌和我的洗牌之间的差距

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:45 25 4
gpt4 key购买 nike

我正在为学校作业编写卡片和牌组类(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或更高版本)。

关于java - 弥合费舍尔耶茨洗牌和我的洗牌之间的差距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com