
Originally Posted by
yannis
The formula I described above allows me to calculate the number of possible combinations of n objects in groups of k, without repetitions. What I want is to find which are these combinations, not how many they are. For example three balls (red,green,blue) combined in groups of two can give three different combinations, without repetitions. I am interested on finding which are these combinations (they are: red-green,red-blue and green-blue). How could I do that for a larger set of objects?
Recursively in Java:
Code:
import java.util.ArrayList;
public class EnumCombs {
static String[] objs = {"cat", "hat", "strategy", "cool", "red", "helicopter"};
static int k = 3, count = 0;
public static void main(String[] args) {
recurse(0, new ArrayList<String>());
System.out.println("\n" + count + " combinations found.");
}
static void recurse(int x, ArrayList<String> comb) {
if(comb.size() == k) {
count++;
System.out.println(comb);
return;
}
if(objs.length - x < k - comb.size()) return;
int i;
for(i = x; i < objs.length; i++) {
ArrayList<String> nextComb = new ArrayList<String>(comb);
nextComb.add(objs[i]);
recurse(i + 1, nextComb);
}
}
} Example is
for a list. Output:
Code:
[cat, hat, strategy]
[cat, hat, cool]
[cat, hat, red]
[cat, hat, helicopter]
[cat, strategy, cool]
[cat, strategy, red]
[cat, strategy, helicopter]
[cat, cool, red]
[cat, cool, helicopter]
[cat, red, helicopter]
[hat, strategy, cool]
[hat, strategy, red]
[hat, strategy, helicopter]
[hat, cool, red]
[hat, cool, helicopter]
[hat, red, helicopter]
[strategy, cool, red]
[strategy, cool, helicopter]
[strategy, red, helicopter]
[cool, red, helicopter]
20 combinations found.