Sunday, September 21, 2025

Permutations and Combinations

 This article was originally posted on JRoller on October 22, 2013

A simple piece of code for calculating all permutations of a given word:

    public static List permutations(String s) {
        List list = new ArrayList<>();
        permutations(list, s, "");
        return list;
    }

    private static void permutations(List list, String from, String to) {
        if (from.isEmpty()) {
            list.add(to);
        }
        else {
            for (int i = 0; i < from.length(); i++) {
                permutations(list,
                        new StringBuilder(from).deleteCharAt(i).toString(),
                        to + from.charAt(i));
            }
        }
    }

The code for permutations of N elements out of a word is a simple modification of the previous program:

    public static List permutationsN(String s, int n) {
        List list = new ArrayList<>();
        permutationsN(list, s, "", n);
        return list;
    }

    private static void permutationsN(List list, String from, String to, int n) {
        if (to.length() == n) {
            list.add(to);
        }
        else {
            for (int i = 0; i < from.length(); i++) {
                permutationsN(list,
                        new StringBuilder(from).deleteCharAt(i).toString(),
                        to + from.charAt(i),
                        n);
            }
        }
    }

For Combinations, that is when order is not important, another small modification does the trick:

    public static List combination(String s, int n) {
        List list = new ArrayList<>();
        combination(list, s, "", 0, n);
        return list;
    }

    private static void combination(List list, String from, String to, int index, int n) {
        if (to.length() == n) {
            list.add(to);
        }
        else {
            for (int i = index; i < from.length(); i++) {
                combination(list,
                        new StringBuilder(from).deleteCharAt(i).toString(),
                        to + from.charAt(i),
                        i,
                        n);
            }
        }
    }

No comments:

Post a Comment