4.0k views
3 votes
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 in java code

User Stb
by
7.3k points

1 Answer

2 votes

Answer:

public class PhotoLineup {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

List<String> names = new ArrayList<>();

String name;

do {

name = input.next();

if (!name.equals("-1")) {

names.add(name);

}

} while (!name.equals("-1"));

Collections.sort(names); // sort the names alphabetically

List<String> chosen = new ArrayList<>();

List<List<String>> permutations = new ArrayList<>();

generatePermutations(names, chosen, permutations);

for (List<String> permutation : permutations) {

System.out.println(String.join(", ", permutation));

}

}

private static void generatePermutations(List<String> names, List<String> chosen, List<List<String>> permutations) {

if (names.isEmpty()) { // base case

permutations.add(new ArrayList<>(chosen));

} else {

for (int i = 0; i < names.size(); i++) {

String name = names.get(i);

chosen.add(name);

names.remove(i);

generatePermutations(names, chosen, permutations);

names.add(i, name);

chosen.remove(chosen.size() - 1);

}

}

}

}

Step-by-step explanation:

The program reads the names from the user input and stores them in an ArrayList. It then sorts the names alphabetically, since we want to output them in alphabetical order as well. It initializes two empty lists: chosen (to keep track of the names chosen so far in each permutation) and permutations (to store all the permutations).

The program then calls the generatePermutations method with the names, chosen, and permutations lists. This method uses a recursive algorithm to generate all possible permutations of the names. It does this by trying each name in turn as the next one in the permutation, and then recursively generating all the permutations of the remaining names. When it reaches a base case (where there are no more names left to choose), it adds the current permutation to the permutations list.

Finally, the program outputs each permutation on a separate line by joining the names with commas using the String.join method.

Hope this helps!

User Andrew Flanagan
by
7.7k points