I am trying to permutate the items in an ArrayList. I'm not getting the right output. I don't know what the issue is, I believe it's in the 'else' loop in the allPermutations method. The list adds all strings until the input is -1
. Sorry if this is a typical question, I tried looking on here before asking but couldn't find any help for myself.
Here is my code:
public static void allPermutations(ArrayList<String> permList,
ArrayList<String> nameList) {
// base case
// nameList is empty after performing all permutations
if (nameList.size() == 0) {
for (int i = 0; i < permList.size(); ++i) {
for (int j = 0; j < permList.size(); ++j) {
System.out.print(permList.get(i) + " ");
}
System.out.println();
}
} else {
for (int i = 0; i < nameList.size(); ++i) {
ArrayList<String> tempPerm = new ArrayList<>(permList);
String name = nameList.get(i);
// remove from nameList and add to new perm
nameList.remove(i);
tempPerm.add(name);
allPermutations(tempPerm, nameList);
}
}
}
The input is:
Julia Lucas Mia -1
The output is supposed to be:
Julia Lucas Mia
Julia Mia Lucas
Lucas Julia Mia
Lucas Mia Julia
Mia Julia Lucas
Mia Lucas Julia
But mine is:
Julia Julia Julia
Lucas Lucas Lucas
Mia Mia Mia