gpt4 book ai didi

java - Fisher-Yates 洗牌时 Java 堆栈中留下的元素?

转载 作者:行者123 更新时间:2023-11-30 04:51:57 26 4
gpt4 key购买 nike

我正在编写的一些代码遇到了一些问题。基本上,我试图像一副纸牌一样“洗牌”堆栈集合,但由于某种原因,我使用的临时堆栈之一不会完全清空,这会在下次运行时导致空集合异常大约。我手动跟踪了代码和输出,元素被留在临时堆栈 1 中(代码如下)。我真的不知道为什么会发生这种情况!如果您对此有任何见解,那将会非常有帮助。

这里是问题方法的链接:http://pastebin.com/cxJCmemZ

public void shuffleCards(LinkedStack<UnoCard> deck) {
int tempIndex;
LinkedStack<UnoCard> tempCardStack1 = new LinkedStack<UnoCard>();
LinkedStack<UnoCard> tempCardStack2 = new LinkedStack<UnoCard>();

//Fisher-Yates shuffle
for (int i = (deck.size() - 1); i >= 0; i--) {
tempIndex = ((int)(i * Math.random()));

System.out.println("i is: " + i);
System.out.println("tempIndex is: " + tempIndex);

//swap if cards are different
if (tempIndex != i) {
//pop face down cards up to first card onto temporary stack
System.out.println("Popping up to first card");
for(int j = 0; j <= tempIndex; j++) {
UnoCard tempCard = faceDownCards.pop();
System.out.println(tempCard.toString());
tempCardStack1.push(tempCard);
}

//pop face down cards up to second card onto temporary stack
System.out.println("Popping up to second card");
for(int j = (tempIndex + 1); j <= i; j++) {
UnoCard tempCard = faceDownCards.pop();
System.out.println(tempCard.toString());
tempCardStack2.push(tempCard);
}

//replace first card in second card position
System.out.println("Replacing first card");
UnoCard tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);

//place second card in temporary stack
System.out.println("Transferring second card");
tempCard = tempCardStack2.pop();
System.out.println(tempCard.toString());
tempCardStack1.push(tempCard);

//replace temporary stack
System.out.println("Replacing second stack");
for(int j = 0; j < tempCardStack2.size(); j++) {
tempCard = tempCardStack2.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
}

//replace second card in first card position
System.out.println("Replacing second card");
tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);

//replace temporary stack
System.out.println("Replacing first stack");
for(int j = 0; j < tempCardStack1.size(); j++) {
tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
}
}
}
}

最佳答案

如果弹出堆栈,大小会缩小,因此 for 循环将仅运行 size/2 次

所以结束循环实际上应该是

while(!tempCardStack1.isEmpty()){
tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
}

关于java - Fisher-Yates 洗牌时 Java 堆栈中留下的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659934/

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