【发布时间】:2025-12-25 01:40:06
【问题描述】:
我在大学里有一个练习要做,其中一部分是制作一副卡片,然后必须洗牌。我将卡片放在一个数组中(未洗牌),并想将它们洗牌并将它们推到自制的堆栈上,我可以从中弹出卡片来处理它们。
我的问题是我想检查我生成的随机数(代表数组中的一张牌)是否已经在堆栈中。通过阅读这个论坛,我想出了下面的代码,在我看来它应该可以工作。在调试时,虽然我注意到重复。
根据我下面的评论,我们不能使用 Collections 框架(编辑)
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]);
}
}
感谢彼得和所有其他贡献者。 M.
【问题讨论】:
-
对不起,我应该说我们不能使用集合框架。
-
为避免重复,请在推送前检查
deck.contains();这应该显示卡片是否已经在洗牌的桌子上。 -
不使用 Collections.shuffle,你可以使用相同的代码。您可以优化代码以随机挑选 N 张牌,而不是洗牌。
-
+1 表示努力并向我们展示代码