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