Suppose I have a list of n lists of string:
For instance when n = 3
list1 = ["M","G"];
list2 = ["VP","P"];
list3 = ["E"]
The output must be a list of all possible combinations with the constraint that each combination must contain one element from each list.
The output of the same example above must be:
2*2*1 = 4 combinations with each combination must contain 3 string exactly (one from each input list).
lists= [ ["M","VP","E"], ["M","P","E"], ["G","VP","E"], ["G","P","E"] ]
I have tried a recursive function but what I noticed is that the current list below can't keep the old version during the recursivity:
lists -> contains all input lists (E.g., list1, list2, and list3)
result -> contains all output lists (all combinations)
current -> is the current combination
public static void combination(ArrayList<ArrayList<String>> lists, ArrayList<ArrayList<String>> result, ArrayList<String> current, int k){
if(k==lists.size()){
result.add(current);
current = new ArrayList<String>();
System.out.println("(if) || k="+k+" || current"+current);
return;
}
for(int t=0;t<lists.get(k).size();t++){
current.add(lists.get(k).get(t));
System.out.println("(for) || k="+k+" || current"+current);
combination(lists, result, current, k+1);
}
}
The output of this function when called with the same example above:
public static void main(String[] args){
ArrayList<String> l1 = new ArrayList<String>();l1.add("M");l1.add("G");
ArrayList<String> l2 = new ArrayList<String>();l2.add("VP");l2.add("P");
ArrayList<String> l3 = new ArrayList<String>();l3.add("E");
ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
ArrayList<String> current = new ArrayList<String>();
lists.add(l1);lists.add(l2);lists.add(l3);
combination(lists, result, current, 0);
for(int i=0;i<result.size();i++){
System.out.println(result.get(i));
}
}
The output is:
(for) || k=0 || current[M]
(for) || k=1 || current[M, VP]
(for) || k=2 || current[M, VP, E]
(if) || k=3 || current[]
(for) || k=1 || current[M, VP, E, P]
(for) || k=2 || current[M, VP, E, P, E]
(if) || k=3 || current[]
(for) || k=0 || current[M, VP, E, P, E, G]
(for) || k=1 || current[M, VP, E, P, E, G, VP]
(for) || k=2 || current[M, VP, E, P, E, G, VP, E]
(if) || k=3 || current[]
(for) || k=1 || current[M, VP, E, P, E, G, VP, E, P]
(for) || k=2 || current[M, VP, E, P, E, G, VP, E, P, E]
(if) || k=3 || current[]
[M, VP, E, P, E, G, VP, E, P, E]
[M, VP, E, P, E, G, VP, E, P, E]
[M, VP, E, P, E, G, VP, E, P, E]
[M, VP, E, P, E, G, VP, E, P, E]
For instance:
This line : (for) || k=1 || current[M, VP, E, P]
must be : (for) || k=1 || current[M, VP]
But current doesn't keep its old version inside the recursive function that called it.