How to print all possible permutations (all possible orderings) of the words in Java

2 Answers

0 votes
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

public class Main {

    public static void print_words_permutations(List<String> words, List<String> current) {
        if (words.isEmpty()) {
            System.out.println(String.join(" ", current));
            return;
        }

        for (int i = 0; i < words.size(); i++) {
            List<String> remaining = new ArrayList<>(words);
            String word = remaining.remove(i);

            List<String> next = new ArrayList<>(current);
            next.add(word);

            print_words_permutations(remaining, next); // Recursive
        }
    }

    public static void main(String[] args) {
        List<String> words = Arrays.asList("word-1", "word-2", "word-3");
        
        print_words_permutations(words, new ArrayList<>());
    }
}



/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz
0 votes
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static boolean nextPermutation(List<String> arr) {
        int i = arr.size() - 2;
        while (i >= 0 && arr.get(i).compareTo(arr.get(i + 1)) >= 0)
            i--;

        if (i < 0) return false;

        int j = arr.size() - 1;
        while (arr.get(j).compareTo(arr.get(i)) <= 0)
            j--;

        Collections.swap(arr, i, j);
        Collections.reverse(arr.subList(i + 1, arr.size()));

        return true;
    }

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("word-1", "word-2", "word-3"));
        Collections.sort(words);

        do {
            System.out.println(String.join(" ", words));
        } while (nextPermutation(words));
    }
}



/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz

Related questions

...