コミュカレでイントロ Java の授業を取っていてだされた宿題に LeetCode 567 Permutation in String に近いものがあったのでトライしてみた。
11.2.1: LAB: 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 into ArrayList nameList
(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.
import java.util.Scanner;
import java.util.ArrayList;
public class PhotoLineups {
// Method to create and output all permutations of the list of names
public static void printAllPermutations(ArrayList<String> permList, ArrayList<String> nameList) {
// Base case: when nameList is empty, print the current permutation
if (nameList.size() == 0) {
System.out.println(String.join(", ", permList));
return;
}
// Iterate through the list and recursively generate all permutations
for (int i = 0; i < nameList.size(); i++) {
// Select the current name
String currentName = nameList.get(i);
// Create a new list of remaining names by removing the current name
ArrayList<String> remainingNames = new ArrayList<>(nameList);
remainingNames.remove(i);
// Add the current name to the permutation list
permList.add(currentName);
// Recurse with the remaining names and current permutation list
printAllPermutations(permList, remainingNames);
// Backtrack: remove the last added name to try the next permutation
permList.remove(permList.size() - 1);
}
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> permList = new ArrayList<>();
String name;
// Read names from the user until "-1" is entered
while (true) {
name = scnr.next().trim();
if (name.equals("-1")) {
break; // Stop reading names when "-1" is encountered
}
nameList.add(name); // Add name to the list
}
// Generate and print all permutations of the list of names
printAllPermutations(permList, nameList);
}
}