Issue
This are the 3 lists that I'm working on:
List<String> first = Arrays.asList("a", "b");
List<String> second = Arrays.asList("X", "Y", "Z");
List<String> third = Arrays.asList("1", "2");
My recursive method for all permutations is the following:
public static void permute(List<List<String>> lists, List<List<String>> result, int depth, String current) {
if (depth == lists.size()) {
List<String> current_list = new ArrayList<>();
current_list = current.chars().mapToObj(e -> Character.toString((char)e))
.collect(Collectors.toList());
result.add(current_list);
return;
}
for (int i = 0; i < lists.get(depth).size(); i++) {
permute(lists, result, depth + 1, current + lists.get(depth).get(i));
}
}
It gives me the following result:
[[a, X, 1], [a, X, 2], [a, Y, 1], [a, Y, 2], [a, Z, 1], [a, Z, 2], [b, X, 1], [b, X, 2], [b, Y, 1], [b, Y, 2], [b, Z, 1], [b, Z, 2]]
How can I change the method so that I get this result instead:
[[a,X, 1], [b, X, 1], [a, Y, 1], [b, Y, 1], [a, Z, 1], [b, Z, 1], [a, X, 2], [b, X, 2], [a, Y, 2], [b, Y, 2], [a, Z, 2], [b, Z, 2]]
Solution
I have not updated your logic but I saw few pattern the the combination happened at the base condition so change the order the input taken in the list and reverse the current list before storing in result.
public class Stack {
static List<List<String>> result = new ArrayList<>();
public static void main(String args[]) {
List<String> first = Arrays.asList("a", "b");
List<String> second = Arrays.asList("X", "Y", "Z");
List<String> third = Arrays.asList("1", "2");
List<List<String>> permute = new ArrayList<>();
permute.add(new ArrayList<>(third));
permute.add(new ArrayList<>(second));
permute.add(new ArrayList<>(first));
permute(permute,result,0,"");
for(List<String> re : result) {
System.out.println(re);
}
}
public static void permute(List<List<String>> lists, List<List<String>> result, int depth, String current) {
if (depth == lists.size()) {
List<String> current_list = new ArrayList<>();
current_list = current.chars().mapToObj(e -> Character.toString((char)e))
.collect(Collectors.toList());
Collections.reverse(current_list);
result.add(current_list);
return;
}
for (int i = 0; i < lists.get(depth).size(); i++) {
permute(lists, result, depth+1, current + lists.get(depth).get(i));
}
}
}
Answered By - Avinash gupta
Answer Checked By - David Marino (JavaFixing Volunteer)