Answer:
import java.util.*;
public class Permutations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
System.out.println("Enter names (enter -1 to stop):");
String name = sc.nextLine().trim();
while (!name.equals("-1")) {
names.add(name);
name = sc.nextLine().trim();
}
List<List<String>> permutations = getPermutations(names);
for (List<String> permutation : permutations) {
System.out.println(String.join(", ", permutation));
}
}
public static List<List<String>> getPermutations(List<String> names) {
List<List<String>> result = new ArrayList<>();
getPermutationsHelper(names, new ArrayList<>(), result);
return result;
}
private static void getPermutationsHelper(List<String> names, List<String> permutation, List<List<String>> result) {
if (names.isEmpty()) {
result.add(permutation);
} else {
for (int i = 0; i < names.size(); i++) {
List<String> newNames = new ArrayList<>(names);
List<String> newPermutation = new ArrayList<>(permutation);
String name = newNames.remove(i);
newPermutation.add(name);
getPermutationsHelper(newNames, newPermutation, result);
}
}
}
}
Step-by-step explanation:
The program starts by reading a list of names entered by the user, terminated by the string "-1". It then calls the getPermutations method to generate all possible permutations of the list of names. The getPermutations method is a recursive function that takes a list of names and a partial permutation, and adds all complete permutations to a result list.
The getPermutationsHelper method is the actual recursive function that generates the permutations. It takes the current list of names, the current partial permutation, and the result list. If the list of names is empty, it means that we have generated a complete permutation, so we add the current permutation to the result list. Otherwise, we loop through the remaining names, remove one name at a time, and recursively call getPermutationsHelper with the remaining names and the updated permutation.
Finally, the program prints out all permutations by looping through the result list and joining the names with commas.