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
I'm late to the party but I followed Shiomi's link and translated the functions into Java. The result is an easy to follow and understand algorithm (I may be a little slow since I had a hard time understanding Bart Kiers' solution).
Here it is (the key is an int, replacing to String should be straightforward):
Usage
public void testProduct(){
Map> data = new LinkedHashMap>(){{
put(0, new ArrayList(){{
add("John"); add("Sarah");
}});
put(1, new ArrayList(){{
add("Red"); add("Green"); add("Blue"); add("Orange");
}});
put(2, new ArrayList(){{
add("Apple"); add("Tomatoe"); add("Bananna");
}});
}};
List product = GetCrossProduct(data);
for(String[] o : product)
System.out.println(Arrays.toString(o));
}
Result
[John, Red, Apple]
[John, Red, Tomatoe]
[John, Red, Bananna]
[John, Green, Apple]
[John, Green, Tomatoe]
[John, Green, Bananna]
[John, Blue, Apple]
[John, Blue, Tomatoe]
[John, Blue, Bananna]
[John, Orange, Apple]
[John, Orange, Tomatoe]
[John, Orange, Bananna]
[Sarah, Red, Apple]
[Sarah, Red, Tomatoe]
[Sarah, Red, Bananna]
[Sarah, Green, Apple]
[Sarah, Green, Tomatoe]
[Sarah, Green, Bananna]
[Sarah, Blue, Apple]
[Sarah, Blue, Tomatoe]
[Sarah, Blue, Bananna]
[Sarah, Orange, Apple]
[Sarah, Orange, Tomatoe]
[Sarah, Orange, Bananna]
Cartesian Product Functions
public static List GetCrossProduct(Map> lists)
{
List results = new ArrayList();
GetCrossProduct(results, lists, 0, new String[(lists.size())]);
return results;
}
private void GetCrossProduct(List results, Map> lists, int depth, String[] current)
{
for (int i = 0; i < lists.get(depth).size(); i++)
{
current[depth] = lists.get(depth).get(i);
if (depth < lists.keySet().size() - 1)
GetCrossProduct(results, lists, depth + 1, current);
else{
results.add(Arrays.copyOf(current,current.length));
}
}
}