【问题标题】:Java: Combinations without repetitionJava:没有重复的组合
【发布时间】:2015-01-22 08:10:28
【问题描述】:

我有一张叫做手牌的列表

Arraylist<Card> hand = new Arraylist<Card>();
hand.add(new Card("As"));
hand.add(new Card("9h"));
...

手牌上限为五张。 我需要通过选择每三张手牌而不重复来获得手中的所有组合,并且顺序并不重要。

例子:

["Ac","10k","5c","7h","3h"]

结果:

[Ac,10k,5c]

[Ac,10k,7h]

[Ac,10k,3h]

[Ac, 5c, 7h]

[Ac, 5c, 3h]

[Ac, 7h, 3h]

[10k, 5c, 7h]

[10k, 5c, 3h]

[10k, 7h, 3h]

[5c, 7h, 3h]

编辑:我确实找到了一个与此相关的已回答问题。

Algorithm to return all combinations of k elements from n

这是java中的一个例子,我稍微调整了一下

public static void main(String[] args){
    Card[] arr = { new Card(16), new Card(4), new Card(22), new Card(16), new Card(11) };
    combinations(arr, 3, 0, new Card[3]);
}

static void combinations(Card[] arr, int len, int startPosition, Card[] result){
    if (len == 0){
        String str = "";
        for(Card card : result)
        {
            str += card.CardString() + ", ";
        }
        System.out.println(str);
        return;
    }       
    for (int i = startPosition; i <= arr.length-len; i++){
        result[result.length - len] = arr[i];
        combinations(arr, len-1, i+1, result);
    }
}

【问题讨论】:

  • 您尝试过什么?你做过研究吗,我有一种直觉,这个问题以前已经解决了……看看所有“相关”的问题
  • 在您的示例中,您手中没有 5 张牌...
  • 我建议拿笔写下所有可能的排列,同时使用列表索引而不是卡片名称。然后你可以弄清楚如何迭代列表索引。
  • 也许你可以在这里找到一些想法:stackoverflow.com/questions/13215593/…

标签: java combinations


【解决方案1】:

好的,你想要一个没有双牌的洗牌。

将您的卡片放入 ArraList。在此之后得到一个介于零和列表大小之间的随机数。 在 plaze x 上获得卡片。然后将其取出并将卡放入您的手中。

 ArrayList<Card> allCards = new ArrayList<Card>();
 .... put all Cards in there
 Card[] hand = new Card[5];
 Random rnd = new Random();
 for(int i = 0;i < 5; ){
  int z = rnd.nextInt(allCards.size());
  Card c = allCards.get(z);
  allCards.remove(z);
  hand[i] = c;
 }

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多