Shuffle deck of cards java

For Shuffle a deck of cards dynamically using java simply just fill array with random numbers between 0 to 51 and then remove one by one when the card is drawn we have here suit between 0 to 3 and rank between 0 to 13.

Now, To create a function to Shuffle a deck of cards dynamically using java.

Create an array of suit from 0 – 3 and rank from 0 – 12. Then add it to an array of deck of length 52 and shuffle the deck array randomly.

public static int[] cardShuffle() {

    // create a deck of 52 cards
    int[] suit = {0, 1, 2, 3};
    int[] rank = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
            11, 12
    };
    int SUITS = suit.length;
    int RANKS = rank.length;

    int N = 52;
    int M = 12;

    int[] deck = new int[N];
    // initialize deck
    for (int j = 0; j < SUITS; j++)
        for (int i = 0; i < RANKS; i++)
            deck[SUITS * i + j] = rank[i] + suit[j] * 13;

    // create random M cards
    for (int i = 0; i < M; i++) {
        int r = i + (int) (Math.random() * (N - i));
        //String t = deck[r];
        int t = deck[r];
        deck[r] = deck[i];
        deck[i] = t;
    }
    return deck;
}

Now function for drawn N cards from the above deck of cards. Suppose you have 3 user each one should contain 4 cards so pass the numberOfCardsDrawn to 3×4 = 12. Then easily you can distribute each one 4 cards.

public static int[] drawCards(int[] deckOfCards,int numberOfCardsDrawn) {
    int[] drawnCards = new int[numberOfCardsDrawn];
    for (int l = 0; l < numberOfCardsDrawn; l++)
        drawnCards[l] = deckOfCards[l];
    return drawnCards;

}

Now just call both the function for the desired result.

    public static void main(String []args){
    int numberOfCardsDrawn = 12;

    int[] deckOfCards =  cardShuffle(); // shuffle cards
    int[] drawCardsFromDeck = drawCards(deckOfCards, numberOfCardsDrawn); // draw cards

    for (int i = 0; i <drawCardsFromDeck.length ; i++) {
        System.out.print(drawCardsFromDeck[i] + ", ");
    }

 }

Then finally take the cards and print by using system out Sample output of the above code snippet

Output: 19, 4, 49, 14, 47, 1, 39, 18, 48, 40, 41, 12

Github link for the code ShuffleCards.java .

Note : Output will be different each time because of the random function used in the program. You can also see other post from here.

Tagged : / / / / /