I have the following 2D array:
String[M][]
String[0]
\"1\",\"2\",\"3\"
String[1]
\"A\", \"B\"
.
.
.
String[M-1]
\"!\"
A
This problem has a very nice recursive structure to it (which also means it could explode in memory, the correct way should be using iterators such as the other answer, but this solution looks nicer imo and we can prove correctness inductively because of the recursive nature). A combination consists of an element from the first list attached to all possible combinations formed from the remaining (n-1) lists. The recursive work is done in AllCombinationsHelper, but you invoke AllCombinations. Note to test for empty lists and more extensively.
public static List AllCombinations(List> aList) {
if(aList.size() == 0) { return new ArrayList(); }
List myFirstSubList = aList.remove(0);
List myStrings = new ArrayList();
for(Character c : myFirstSubList) {
myStrings.add(c.toString());
}
return AllCombinationsHelper(aList, myStrings);
}
public static List AllCombinationsHelper(List> aList,
List aCollection) {
if(aList.size() == 0) { return aCollection; }
List myFirstList = aList.remove(0);
List myReturnSet = new ArrayList();
for(String s : aCollection) {
for(Character c : myFirstList) {
myReturnSet.add(c + s);
}
}
return AllCombinationsHelper(aList, myReturnSet);
}