制作所有可能的扑克牌(牌组)

时间:2016-08-09 12:24:53

标签: java collections

让我们说我试图用标准扑克牌模拟比赛。

我有这样的事情:

public enum Suit { HEART, DIAMONDS, SPADES, CLUBS }

等等:

VersionCtrlRestClient

如何创建集合最适合的对象(如集合或链表),以及集合中每对对象应该是什么类型的对象。

3 个答案:

答案 0 :(得分:1)

这是制作enum套装,enum等级然后循环enum#values的良好模式。

Olien04有suggested a similar approach,但他的代码没有编译。出于这个原因,我已经使用构造函数和toString方法添加了这个答案。

enum Suit {HEART, DIAMONDS, SPADES, CLUBS}
enum Rank {TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE}

public class Card {
    Rank rank;
    Suit suit;
    public Card (Rank r, Suit s) {rank = r; suit = s;} //public constructor
    @Override
    public String toString() {
        return rank.toString() + " " + suit.toString();
    }
}

ArrayList<Card> deck = new ArrayList<>();
for (Suit s : Suit.values()) {
    for (Rank r : Rank.values()) {
        deck.add(new Card(r, s));
    }
}
System.out.println(deck.toString());

答案 1 :(得分:0)

就像@Progressive_overload评论一样,这可能是最好的方法。

卡类:

enum Suit {HEART, DIAMONDS, SPADES, CLUBS}
enum Rank {TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE}
class Card {
   public Rank rank;
   public Suit suit;

   public Card (Rank r, Suit s) {
     rank = r; suit = s;
   }
}

生成:

List<Card> deck = new ArrayList<Card>();

for (Suit s : Suit.values()) {
  for (Rank r : Rank.values()) {
    deck.add(new Card(r, s));
  }
}

答案 2 :(得分:-1)

我认为通过有序对(a,b),你的意思是a.face&lt; = b.face,并且你不希望成对两次相同的牌。您只需要一个嵌套循环,在该循环中迭代条件为真的所有值并将它们添加到列表中(这样您就可以保留每对第一张卡的排序顺序值,以便于验证)。

import java.util.ArrayList;
import java.util.List;

public class CardPairs
{

    static char[] faces = {'2','3','4','5','6','7','8','9','T','J', 'Q', 'K', 'A'};
    static enum Suit { HEART, DIAMONDS, SPADES, CLUBS };

    static class Card
    {
        final char face;
        final Suit suit;

        public Card(char face, Suit suit) {this.face=face;this.suit=suit;}
        @Override public String toString() {return face+" "+suit;}
    }

    static public class CardPair
    {
        final Card first;
        final Card second;

        public CardPair(Card first, Card second) {this.first=first;this.second=second;}
        @Override public String toString() {return "("+first+", "+second+")";}
    }

    public static void main(String args[])
    {
        List<CardPair> allPairs = new ArrayList<CardPair>();
        for(int i=0;i<faces.length;i++)
            for(int j=i;j<faces.length;j++)
                for(Suit suit1: Suit.values())
                    for(Suit suit2: Suit.values())
                    {
                        {
                            if(suit1!=suit2||i!=j) // assuming you don't want pairs of the same card
                            {
                            allPairs.add(new CardPair(new Card(faces[i],suit1),new Card(faces[j],suit2)));
                            }
                        }
                    }
        System.out.println(allPairs);
    }
}