105k views
4 votes
in java 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 Genee
by
8.8k points

1 Answer

5 votes

Answer:

Here's an example Java code that can print all permutations of names given as input:

Step-by-step explanation:

import java.util.Scanner;

public class Permutations {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String[] names = new String[10];

int n = 0;

// read the names from input and store them in an array

while (input.hasNext()) {

String name = input.next();

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

break;

}

names[n++] = name;

}

// call the method to print all permutations of names

printPermutations(names, 0, n-1);

}

// recursive method to print all permutations of names

public static void printPermutations(String[] names, int left, int right) {

if (left == right) {

// base case: if left and right are equal, it means we have reached the end of the name list

for (int i = 0; i <= right; i++) {

if (i == right) {

System.out.print(names[i]); // print the last name without a comma

} else {

System.out.print(names[i] + ", "); // print the name with a comma after it

}

}

System.out.println(); // print a new line after printing the names

} else {

// recursive case: perform permutations of names at different positions

for (int i = left; i <= right; i++) {

// swap the name at position i with the name at position left

String temp = names[left];

names[left] = names[i];

names[i] = temp;

// perform permutations at position left+1

printPermutations(names, left+1, right);

// swap the name at position i back to its original position

names[i] = names[left];

names[left] = temp;

}

}

}

}

User Pumych
by
8.8k points