I'm writing a recursive permutations program in Java to find all the possible permutation of the Strings in an Arraylist. I know there are a lot of posts similar to this, but I haven't found one that addresses this issue specifically.
The problem I have with my code is that it only runs the first permutation and then quits
I know that it's doing this because every time it is called, an item is removed but the indexes shift so its only doing one call per element, but I don't know how to fix it. I've tried changing the for-loop conditions, removing the element at different spots, adding base cases, but everything seems to only make it worse. As it is now, the input[w,h,a,t]
would return an arrayList with elements [what,hat,at,t]
. The expected output is all the permutations of the four letters.
Where do I go from here? I know I'm close but I've been stuck on this for several days
Any help would be greatly appreciated
public class wordFinder {
static ArrayList<String> permutations = new ArrayList<String>();
public static String findPermutations(ArrayList<String> letterArray) {
String prefix = "";
for (int i = 0; i < letterArray.size(); i++) {
String temp = letterArray.remove(i);
prefix = temp + findPermutations(letterArray);
permutations.add(prefix);
}
return prefix;
}
}