I have n Sets. each Set has different number of elements. I would like to write an algorithm which give me all possible combinations from the sets. for example: Lets say we have
Great solution by krilid, I modified it a bit to return a list of all combinations.
@Test
public void testMap() throws Exception {
char[] one = new char[]{'a', 'b', 'c'};
char[] two = new char[]{'d', 'e', 'f'};
char[] three = new char[]{'g', 'h', 'i', 'j'};
char[][] sets = new char[][]{one, two, three};
List> collector = new ArrayList<>();
ArrayList combo = new ArrayList<>();
combinations(collector, sets, 0, combo);
System.out.println(collector);
}
private void combinations(List> collector, char[][] sets, int n, ArrayList combo) {
if (n == sets.length) {
collector.add(new ArrayList<>(combo));
return;
}
for (char c : sets[n]) {
combo.add(c);
combinations(collector, sets, n + 1, combo);
combo.remove(combo.size() - 1);
}
}