gpt4 book ai didi

java - 重复数组中的值并将其打乱

转载 作者:行者123 更新时间:2023-12-02 05:31:45 29 4
gpt4 key购买 nike

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

每张卡牌必须 self 复制 4 次才能完成一副包含 40 张卡牌的牌,然后将其洗牌。我如何使用 Java 来做到这一点?

最佳答案

首先,你有一点物体恐惧症。让我们从 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 setters ,还有 toString , equals 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());

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

关于java - 重复数组中的值并将其打乱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472127/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com