KrakenJaws
KrakenJaws

Reputation: 155

How to shuffle cards within a Card object with Math.random()

So the problem is I am not getting any card rank or value of card such as a number 2-14 and my characters 'C', 'D', 'H', 'S' seem to get shuffled.

How would I go about shuffling an object containing

new Card(int, char)

with characters 'C', 'D', 'H', 'S' which represent the cards suit.

This code below does not seem to work as in saving any rank numbers.

for (int i = 0; i <= 51; i++)           
cards[i] = new Card((int)Math.random() * 52, 'D');

An example of how the shuffling should work if card [14] randomly generates integer 35, then card[14] would swap with card[35].

public void shuffle()
{
    for (int i = 0; i <= 51; i++)           
        cards[i] = new Card((int)Math.random() * 52, 'D');

    for (int i = 0; i <= 51; i++) {     
        Card temp = cards[i];
        for (int j = 0; j <= 51; j++) {
            cards[i] = cards[j];
            cards[j] = temp;
        }
    }
}

Upvotes: 2

Views: 1369

Answers (4)

Mok
Mok

Reputation: 287

1.public void shuffle()
2.{
3.for (int i = 0; i <= 51; i++)           
4.    cards[i] = new Card((int)Math.random() * 52, 'D');

5.for (int i = 0; i <= 51; i++) {     
6.    Card temp = cards[i];
7.    for (int j = 0; j <= 51; j++) {
8.        cards[i] = cards[j];
9.        cards[j] = temp;
    }
}
}

At the first iteration inside the j-loop, you are setting every card[0-52] as temp. Hence you are ending up copying first card to all of them.

Best solution here would be to use the existing shuffle functionality from collections

List<Card> myCards = new ArrayList<>();
//Add your cards
Collections.shuffle(myCards);

Upvotes: 0

Marv
Marv

Reputation: 3557

You could use an ArrayList instead of an array and then use

List<Card> myCards = new ArrayList<>();
//Add your cards
Collections.shuffle(myCards);

Upvotes: 0

aioobe
aioobe

Reputation: 421040

I would suggest you first create the deck, then shuffle it.

// Create deck
Card[] cards = new Card[52];
int i = 0;
for (int v = 2; v <= 14; v++)
    for (char s : "CDHS".toCharArray())
        cards[i++] = new Card(v, s);

// Shuffle
Collections.shuffle(Arrays.asList(cards));

Upvotes: 2

roeygol
roeygol

Reputation: 5038

Create a list which contains all of the cards deck.

Create a loop to random some number between zero and the list side, each time you're getting a number just remove this item from the list and put it in some shuffeld list.

You can also use:

Collections.shuffle(yourList);

Upvotes: 0

Related Questions