gpt4 book ai didi

java - 检查数组中的整数

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:06 25 4
gpt4 key购买 nike

我在大学里有一项练习要做,其中一部分是制作一副纸牌,然后必须将其洗牌。我将卡片排列成一个阵列(未洗牌),我想将它们洗牌并将它们推到自制的 Stack 上,我可以从中取出卡片来发牌。

我的问题是我想检查我生成的随机数(代表数组中的一张卡片)是否已经在堆栈中。通过在这个论坛上阅读,我想出了下面的代码,在我看来它应该可以工作。在调试时,虽然我注意到重复项。

根据我在下面的评论,我们不能使用集合框架(编辑)

private Stack<Card> deck;//to hold cards
private Card[] protoDeck;//to hold cards before shuffling
private Random randomer;

private int cardsDealt;//how many cards used. Used for other methods
private static final int TOTALCARDS = 52;//sets limit of deck for all decks

public void shuffle(){//remove cards from deck and put back in random order
randomer = new Random();
int[] temp = new int[TOTALCARDS];//to keep track of random numbers
int rand = 0;

for (int i = 0; i < temp.length ; i++) {
do {//keep creating randoms if
rand = randomer.nextInt(TOTALCARDS);
deck.push(protoDeck[rand]);//puts the Card onto the Deck in a random position
temp[i] = rand;
} while (!(Arrays.asList(temp).contains(rand)));//check if the number already used
}
}

@PeterLawrey 我已经稍微调整了代码,如下所示,因为我只需要洗整副牌就可以了,我会把牌从牌堆中取出来发牌


public void shuffle() {
randomer = new Random();
for(int i = 0; i < TOTALCARDS; i++) {
// pick a random card from the rest of the deck
int j = randomer.nextInt(protoDeck.length - i) + i;
// swap cards
Card tmp = protoDeck[i];
protoDeck[i] = protoDeck[j];
protoDeck[j] = tmp;
deck.push(protoDeck[i]);
}

}

感谢彼得和所有其他贡献者。

最佳答案

开始于

private final Card[] deck;//to hold cards before shuffling
private final Random rand = new Random();

你可以做到

public void shuffle() {
// no need the shuffle the last card.
shuffle(deck.length - 1);
}

// will leave the first N card random without duplicates.
public void shuffle(int numberOfCards) {
for(int i = 0; i < numberOfCards; i++) {
// pick a random card from the rest of the deck
int j = rand.nextInt(protoDeck.length - i) + i;
// swap cards
Card tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
}

成本是 O(N),其中 N 是随机卡的数量。


假设你有一个像这样的小 Deck

AS AC AD AH 2S 2C 2D 2H

你需要随机选择第一张牌,从牌组中选择一张并交换那张牌。假设 nextInt() 是 5 => 2C

2C | AC AD AH 2S AS 2D 2H

table 由随机​​选择+未选择的卡片组成。您没有重复的卡片,因为相同的卡片会四处移动。下一张随机卡是 2H,它与 AC 交换

2C 2H | AD AH 2S AS 2D AC

最后恰好选中了AD。

2C 2H AD | AH 2S AS 2D AC

这会为您提供三张随机卡片和其余卡片。可以再次使用相同的数组,因为从排序的或随机的牌组开始不会使结果或多或少随机。


在回复答案Why does this simple shuffle algorithm produce biased results?如果有123,可能的结果是

123
+- 123 - swap 1 and 1 (these are positions, not numbers)
| +- 123 - swap 2 and 2
| +- 132 - swap 2 and 3
+- 213 - swap 1 and 2
| +- 213 - swap 2 and 2
| +- 231 - swap 2 and 3
+- 321 - swap 1 and 3
+- 321 - swap 2 and 2
+- 312 - swap 2 and 3

如您所见,只有 6 种可能的结果,而且可能性均等。

关于java - 检查数组中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292197/

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