Search code examples
javaplaying-cards

How to shuffle an array


I have an question about how to shuffle an array. The background is:
Write a memory matching game, which using 16 cards that laid out in a 4*4 square and are labeled with pairs of number from 1 to 8.

Currently, what I need to do is to initialize these cards and shuffle these cards.

And now what I can think of is that creating a Card class including variable Rank from 1 to 8, secondly, naming a new class (matchingGame)(whatever you like) and writing a new static method: shuffle().

But I am stuck at this step.

My first question is how to initialize these 16 cards (8 pairs)?
(I think my code is not the efficient way).

My second question is how to shuffle cards after initialization?

My code is:

public class Card 
{
private int rank;

public Card(int iniRank)
{
    switch (iniRank)
    {
    case 1:
        rank =1;
        break;
    case 2:
        rank =2;
        break;
    case 3:
        rank =3;
        break;
    case 4:
        rank =4;
        break;
    case 5:
        rank =5;
        break;
    case 6:
        rank =6;
        break;
    case 7:
        rank =7;
        break;
    case 8:
        rank =8;
        break;
    }
}

public int getRank()
{
    return rank;
}


}


public static void initialize(Card[] cards)
{
    for (int i=0;i<2;i++)
    {
        cards[i] = new Card(1);
    }
    for (int i=2;i<4;i++)
    {
        cards[i] = new Card(2);
    }
....
}    

Thanks everyone for my previous question!
Just one more question in the same background, As your good advice, you know how to shuffle a 1D array?

But how to shuffle a 2D array? Obviously, I cannot use

List<Card> newcards = Arrays.asList(cards) 

for converting to List now.

Thanks for ur help


Solution

  • Your method for initializing the array is essentially correct: loop through your array and add a new instance at each point.

    Card[] cards = ...;
    for (int i = 0; i < cards.length; i++)
        cards[i] = ...  // new Card instance
    

    Now for shuffling - don't reinvent the wheel: Use Collections.shuffle:

    Card[] cards = ...;
    List<Card> l = Arrays.asList(cards);
    Collections.shuffle(l);