99.2k views
5 votes
n java program code All permutations of names Write a program that lists all ways people can line up for a photo (all permutations of a list of Strings). The program will read a list of one word names (until -1), and use a recursive method to create and output all possible orderings of those names separated by a comma, one ordering per line. When the input is: Julia Lucas Mia -1 then the output is (must match the below ordering): Julia, Lucas, Mia Julia, Mia, Lucas Lucas, Julia, Mia Lucas, Mia, Julia Mia, Julia, Lucas Mia, Lucas, Julia

User Tocs
by
8.6k points

1 Answer

4 votes

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.

User ATei
by
8.6k points