hydregion hydregion - 5 months ago 14
Java Question

How to shuffle a deck of cards into 2 hands

I have this homework assignment, where our teacher wants us to create the card game "War" in java. A huge part of it, is shuffling the 52 different cards into two players hands. I would greatly appreciate any help for when it comes to shuffling it. I am an inexperienced coder, and the other ones posted don't make any sense for me.
My code:

package shuffle;

import java.util.Random;

public class SHUFFLE {

public static void main(String[] args) {
shuffle();
}

public static void shuffle() {
Random r = new Random();
int[] hand1 = new int[26];
int[] hand2 = new int[26];
int i = 1, rand, rand2;
int o = 1;
do {
System.out.println("Top");
rand = r.nextInt(52) + 1;
rand2 = r.nextInt(2) + 1;
System.out.println("number generated: "+rand);
System.out.println("sector: " + rand2);
if (rand2 == 1) {
if (rand <= 52) {
while (hand1[o] > 0) {
if (hand1[o] == rand) {
} else {
hand1[o]--;
}
}
while (hand2[i] > 0) {
if (hand2[i] == rand) {
} else {
hand2[i]--;
}
hand1[o] = rand;
o++;
}
}

}

if (rand2 == 2) {
if (rand <= 52) {
while (hand1[o] > 0) {
if (hand1[o] == rand) {
} else {
hand1[o]--;
}
}
while (hand2[i] > 0) {
if (hand2[i] == rand) {
} else {
hand2[i]--;
}
hand2[i] = rand;
i++;
}
}

}

}while(hand1[o] < 26 && hand2[i] < 26);
}

}

Answer

Don't waste time shuffling the deck before-hand, the Fisher Yates shuffle is a far more efficient way of selecting cards at random from even a sorted deck.

You can see this answer to learn how it's done then it's basically using that algorithm to distribute the selected cards to alternate hands.

So, bottom line (pseudo-code since it's classwork), you can use the following to create two hands of twenty-six cards each (with one-based arrays):

# Set up deck of cards with initial size, and empty hands.

cards[] = [acespades, twospades, ..., queenhearts, kinghearts]
quant = size(cards)

hand1 = []
hand2 = []

# Need to distribute entire deck.

while quant > 0:
    # Get card for first hand using Fisher Yates shuffle

    index = random(1..quant)
    hand1.append(cards[index])
    cards[index] = cards[quant]
    decrement quant

    # If no cards left, exit the loop.

    if quant == 0:
        exit while

    # Now get card for second hand.

    index = random(1..quant)
    hand2.append(cards[index])
    cards[index] = cards[quant]
    decrement quant

Note the extra check in there for if your original deck has an odd number of cards (the if ... exit while bit). If you know the deck will be even, this is not needed - I've just put it in there for cases where the deck size is not known before-hand).

Also note that there is opportunity for refactoring the code that deals a card so that you don't have it repeated. I'll leave that as an educational exercise.

Comments