# Thread: Shuffling a deck of cards

1. Member
Join Date
Apr 2014
Location
Miami, FL
Posts
47
Rep Power
0

## Shuffling a deck of cards

Assuming we have an array that is int[] cardDeck = new int[52] and each card is given a value with the following method; this deck does not include Jokers. Note: 11, 12, and 13 and used to represent Jacks, Queens, and Kings respectively, and 1 is used to represent Aces.
Java Code:
```public static void loadDeck(int[] cardDeck)
{
for(int i = 0; i < cardDeck.length; i++)
{
if(i+1 > 39)
cardDeck[i] = i+1-39;
else if(i+1 > 26)
cardDeck[i] = i+1-26;
else if(i+1 > 13)
cardDeck[i] = i+1-13;
else
cardDeck[i] = i+1;
}
}```
I am attempting to shuffle the "cards" or integers in my array with the following method. I am getting an ArrayIndexOutOfBoundsException, so I would appreciate an explanation of how to fix this. Here is my code.
Java Code:
```public static void shuffleDeck(int[] cardDeck)
{
int number = (int) Math.random()*50 + 1;
for(int i = 0; i < cardDeck.length; i++)
{
if(i+number > 52)
cardDeck[i] = cardDeck[i+number];
cardDeck[i] = cardDeck[i+number];
}
}```

2. ## Re: Shuffling a deck of cards

If in the loop i is going up to the max allowed index, won't i+number go past the max index value?

Can you explain the logic of the shuffle method? The code doesn't make sense to me.

3. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
3,417
Rep Power
5

## Re: Shuffling a deck of cards

I suggest you look up shuffling algorithms on the web. There are plenty of sites. You can also search this forum since the topic was covered extensively within the last year. Also, your method loadDeck would be easier to read if you modified it like this:

Java Code:
```if(i> 38)  {
cardDeck[i] = i-38;
} else if ...
// and so forth```
But you could simplify it alot if you would employ the % operator. Just think about it.

Regards,
Jim

4. Member
Join Date
Apr 2014
Location
Miami, FL
Posts
47
Rep Power
0

## Re: Shuffling a deck of cards

Finally fixed the problem using the Fisher-Yates shuffle algorithm. My logic to shuffle the deck was completely incorrect to discard that. I will post the code for future reference.
Java Code:
```public static void shuffleDeck(int[] cardDeck)
{
Random random = new Random();
for(int i = cardDeck.length - 1; i > 0; i--)
{
int index = random.nextInt(i + 1);
int a = cardDeck[index];
cardDeck[index] = cardDeck[i];
cardDeck[i] = a;
}
}```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•