How to make a combination of strings and make an array of it?

Viewed 212

I want the user to enter 3 names and the program will make 6 combinations of it. After, ask the user again to select a name by entering a number based on the combination of names. For example the user inputs: name1, name2 and name3. The combinations would be: name1 name2, name1 name 3, name2 name 1, name2 name3, name3 name1, name3 name2. And the user will pick from those combinations by entering a number associated with the combinations. I've tried doing it but can't really get on how to make the combinations.

import java.util.Scanner;
public class Strings1 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    
    System.out.println("Please enter 3 names: ");
    String name1 = input.nextLine();
    String name2 = input.nextLine();
    String name3 = input.nextLine();
    String names[] = {name1, name2, name3};
    
    
    System.out.println("Possible combinations are: ");
    
    for (int i = 1; i <= 6; i++) {
        System.out.println(i + " - " + names[0] + " " + names[1]);  
    }
}
}
1 Answers
public static void main(String[] args) {
         Scanner input = new Scanner(System.in);

         System.out.println("Please enter 3 names: ");
         String name1 = input.nextLine();
         String name2 = input.nextLine();
         String name3 = input.nextLine();
         String names[] = {name1, name2, name3};
            
         permutationRecursive(names.length, names, ' ');
        
         System.out.println("Possible combinations are: " + combincations.toString());
    }
    
    private static ArrayList<String> combincations = new ArrayList<>();
    
    public static void permutationRecursive(int n, String[] elements, char delimiter) {
        if (n == 1) {
            String combinationString = printArray(elements, delimiter);
            combincations.add(combinationString);
        } else {
            for (int i = 0; i < n - 1; i++) {
                permutationRecursive(n - 1, elements, delimiter);
                if (n % 2 == 0) {
                    swap(elements, i, n - 1);
                } else {
                    swap(elements, 0, n - 1);
                }
            }
            permutationRecursive(n - 1, elements, delimiter);
        }
    }

    private static void swap(String[] input, int a, int b) {
        String tmp = input[a];
        input[a] = input[b];
        input[b] = tmp;
    }

    private static String printArray(String [] input, char delimiter) {
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < input.length; i++) {
            strBuilder.append(input[i]);
            strBuilder.append(delimiter);
        }
        return strBuilder.toString().substring(0, strBuilder.length()-1);
    }
Related