I have a problem that is really kind of a general programming question, but my implementation is in Java, so I will provide my examples that way
I have a class like
Take a look at the following two methods, they do exactly what you asked for. I wrote them to be generic, it doesn't matter how long your lists are or how many keys exist in the map, the combinations generated are correct.
The code below is iterative, based on the algorithm of Python's itertools.product() function for calculating the Cartesian product of a list of lists.
public String[][] allUniqueCombinations() {
List labels = new ArrayList();
List> lists = new ArrayList>();
for (Map.Entry> entry : dataStructure.entrySet()) {
labels.add(entry.getKey());
lists.add(entry.getValue());
}
List> combinations = product(lists);
int m = combinations.size() + 1;
int n = labels.size();
String[][] answer = new String[m][n];
for (int i = 0; i < n; i++)
answer[0][i] = labels.get(i);
for (int i = 1; i < m; i++)
for (int j = 0; j < n; j++)
answer[i][j] = combinations.get(i-1).get(j);
return answer;
}
private List> product(List> lists) {
List> result = new ArrayList>();
result.add(new ArrayList());
for (List e : lists) {
List> tmp1 = new ArrayList>();
for (List x : result) {
for (String y : e) {
List tmp2 = new ArrayList(x);
tmp2.add(y);
tmp1.add(tmp2);
}
}
result = tmp1;
}
return result;
}
I tested them with the example in the question:
LinkedHashMap> sample =
new LinkedHashMap>();
Vector v1 = new Vector();
v1.add("1"); v1.add("2"); v1.add("3");
Vector v2 = new Vector();
v2.add("3"); v2.add("2");
Vector v3 = new Vector();
v3.add("5"); v3.add("6"); v3.add("7");
sample.put("foo", v1);
sample.put("bar", v2);
sample.put("baz", v3);
Foo foo = new Foo(sample);
String[][] ans = foo.allUniqueCombinations();
for (String[] row : ans)
System.out.println(Arrays.toString(row));
The answer that gets printed is the expected (although the combinations appear in a different order):
[foo, bar, baz]
[1, 3, 5]
[1, 3, 6]
[1, 3, 7]
[1, 2, 5]
[1, 2, 6]
[1, 2, 7]
[2, 3, 5]
[2, 3, 6]
[2, 3, 7]
[2, 2, 5]
[2, 2, 6]
[2, 2, 7]
[3, 3, 5]
[3, 3, 6]
[3, 3, 7]
[3, 2, 5]
[3, 2, 6]
[3, 2, 7]