0

I have a list of cards called hand

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

The maximum limit of cards in hand is five. I need to get all the combinations in the hand by choosing every three of cards in hand without repetitions and the order is not important.

Example:

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

Result:

[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]

Edit: I did find an answered question related to this.

Algorithm to return all combinations of k elements from n

Here is one of the example in java and I tweak it a little bit

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);
    }
}
Community
  • 1
  • 1
khepri
  • 77
  • 1
  • 10
  • 6
    What have you tried yet? Have you done your research, I have a gut feeling that this problem has been solved before... take a look at all the "Related" questions – reto Jan 22 '15 at 08:11
  • You don't have 5 cards in the hand in your example... – Nir Alfasi Jan 22 '15 at 08:19
  • I would recommend to take a pen and write down all the possible permutations while using the lists index instead of the cards name. Then you can figure out how to iterate over the lists indices. – Bullaface Jan 22 '15 at 08:20
  • Maybe yuou cand find some ideas here: http://stackoverflow.com/questions/13215593/combination-and-permutation-algorithms-recursive – Jordi Castilla Jan 22 '15 at 08:55

0 Answers0