views:

130

answers:

3

Hi,

I have a standard deck of cards and then have removed a few, from the remaining cards I want to calculate all of the possible two card combinations. For example with 47 cards there is 47 choose 2 combinations. Can anyone think of an efficient way to do this other than

foreach(card){
  combinations.add(card, card +1)
}

Thanks

+3  A: 
for(int i=0; i<47; i++) {
  for(int j=i+1; j<47; j++) {
     combinations.add(i, j);
  }
}

This is the most efficient way, as it goes through each pair only once.

If you just want the number of two-pair combinations, see here.

BlueRaja - Danny Pflughoeft
+1  A: 

On this site there are some algorithms solving combinatoric problems. Look for a class called

class ChoiceIterable<T> implements Iterable<T[]>
tangens
+1  A: 

If all you need is just two card subsets (as opposed to a variable number), you could easily do this with two nested for loops.

for(i=0;i<cards.length;i++){
   for(j=i+1;j<cards.length;j++){
      combinations.add(cards[i],cards[j]);
   }
}
MAK