# 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.

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Tagged : / / / / /

## 2 thoughts on “Shuffle deck of cards java”

1. waterfallmagazine.com says:

https://waterfallmagazine.com
You actually make it seem so easy with your presentation but
I find this topic to be actually something which I think I would never understand.
It seems too complex and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

1. Aman Shukla says:

Hi you can easily understand this topic for further description I will update another post about this

Stay tuned thanks