0

I'm having trouble shuffling a two dimensional array in Java. There are 10 base cards.

This is the array:

String[][] Cards = new String[][] {
        {"CardType1","CardName1","CardProperties"},
        {"CardType1","CardName2","CardProperties"},
        {"CardType1","CardName3","CardProperties"},
        {"CardType2","CardName4","CardProperties"},
        {"CardType2","CardName5","CardProperties"},
        {"CardType2","CardName6","CardProperties"},
        {"CardType2","CardName7","CardProperties"},
        {"CardType3","CardName8","CardProperties"},
        {"CardType3","CardName9","CardProperties"},
        {"CardType3","CardName10","CardProperties"}
        };

Each card must replicate itself 4 times to complete a deck with 40 cards and then shuffle it. How can I use Java to do this?

1 Answers1

2

First, you have a little object phobia. Lets start with an enum for CardType:

public enum CardType {
    TYPE_1,
    TYPE_2,
    TYPE_3,
    //etc...
    ;
}

Not sure what card name is, but lets leave it as a String. Not sure what card properties is either - lets call this a Map<String, String>. So our Card class would be something like:

public class Card {
    private final CardType cardType;
    private final String cardName;
    private final Map<String, String> properties = new HashMap<>();

    Card(final CardType cardType, final String cardName) {
        this.cardType = cardType;
        this.cardName = cardName;
    }

    public Card setProperty(final String name, final String value) {
        properties.put(name, value);
        return this;
    }

    public String getProperty(final String name) {
        return properties.get(name);
    }
}

Add getters and setters, also toString, equals and hashCode methods. Possibly make Card implement Comparable<Card>.

So to create a Card you would call:

final Card card = new Card(CardType.TYPE_1, "CardName1");

And to set properties, because the method is chainable you can do:

final Card card = new Card(CardType.TYPE_1, "CardName1").
        setProperty("prop1", "thing").
        setProperty("prop2", "stuff");

Now, to create your deck, you need 4 cards of each type, this is simple. With Java 8:

final List<Card> deck = Stream.of(CardType.values()).
        flatMap(type -> IntStream.rangeClosed(1, 4).mapToObj(num -> new Card(type, "CardName" + num))).
        collect(toList());

Pre Java 8 to create the List you can use explicit loops:

final List<Card> deck = new LinkedList<>();
for (final CardType cardType : CardType.values()) {
    for (int i = 1; i <= 4; ++i) {
        final Card card = new Card(cardType, "CardName" + i);
        deck.add(card);
    }
}

In order to shuffle a Collection simply use Collections.shuffle like so:

Collections.shuffle(deck);
Community
  • 1
  • 1
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166