I have an exercise to do in college, part of which consists of creating a pack of cards which must then be shuffled. I have the cards in an array (not shuffled) and want to shuffle them and push them onto a home made Stack, from which I can pop the cards off to deal them.
My problem is that I want to check that the random number I generate (and which represents one of the cards in the array) is not already in the Stack. From reading on this forum I have come up with the code below which, it seems to me should work. On debugging though I notice duplicates.
As per my comment below we can't use the Collections framework (edit)
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 I have tweaked the code slightly as follows as I only need to shuffle full decks and it works a treat, I will pop cards off the Stack to deal
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]);
}
}
Thanks to Peter and all the other contributors. M.
deck.contains()
before pushing; that should show if the card is already in the shuffled desk. – Reduction