Permuting Lists of Lists - Print all possible words from phone digits - Algorithms and Problem SolvingAlgorithms and Problem Solving
Read full article from Permuting Lists of Lists - Print all possible words from phone digits - Algorithms and Problem SolvingAlgorithms and Problem Solving
Given a list of arraylists containing elements, write a function that prints out the permutations of of the elements such that, each of the permutation set contains only 1 element from each arraylist and there are no duplicates in the list of permutation sets.
For example: consider the following lists
L1= {a1,b1,c1,d1} L2= {a2,b2,c2} L3= {a3, b3, c3} Valid Permutations are: {a1, a2, a3} {a1, a2, b3} {a1, a2, c3} {a1, b2, a3} {a1, b2, b3} {a1, b2, c3} ... ... ... {d1, c2, a3} {d1, c2, b3} {d1, c2, c3} Please note that {a1,b2,c3} is same set as {b2,a1,c3}
We can solve this problem similar to we did solve the combination problem in a previous post here. This problem can be solved similarly where we consider the the input list as a multidimensional string that contains a list of string at each position. Anytime we will consider one single item. So, for each string in first list we do recurse to all other lists to find the combinations. We print the result whenever we reach the last list and output contains one elements from each of the n lists.
public static void permuteList(String[][] list, int start, ArrayList<String> perms // use linkedlist){ if(start == list.length){ if(perms.size() == list.length) System.out.println(perms.toString()); return; } for(int i = 0; i < list[start].length; i++){ perms.add(list[start][i]); for(int j = start+1; j <= list.length; j++){ permuteList(list, j, perms); }// change to perms.removeLast(); perms.remove(list[start][i]); // change to remove perms.remove(perms.size() - 1); } }