在数组中重复值并将其洗牌

时间:2014-08-24 13:19:58

标签: java arrays shuffle

我在Java中乱码二维数组时遇到了麻烦。有10张基本卡。

这是数组:

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"}
        };

每张卡必须复制4次以完成带有40张牌的牌组,然后将其洗牌。我如何使用Java来做到这一点?

1 个答案:

答案 0 :(得分:2)

首先,你有一个小对象恐惧症。让我们从enum开始CardType

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

不确定卡的名称是什么,但请将其保留为String。不确定卡属性是什么 - 让我们称之为Map<String, String>。所以我们的Card类就像:

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);
    }
}

添加getters and setterstoStringequals and hashCode方法。可能会Card implement Comparable<Card>

所以要创建一个Card,你可以打电话:

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

要设置属性,因为方法为chainable,您可以执行以下操作:

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

现在,要创建你的套牌,每种类型需要4张牌,这很简单。使用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创建List您可以使用显式循环:

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);
    }
}

为了对Collection进行随机播放,只需使用Collections.shuffle,就像这样:

Collections.shuffle(deck);