Quantcast
Channel: Scratch Where It's Itching
Viewing all articles
Browse latest Browse all 73

N Permutations and Combinations

$
0
0
Following my last entry, I would like to add the code for permutations of N elements out of a word, which 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);            }        }    }


Viewing all articles
Browse latest Browse all 73

Trending Articles