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 ListpermutationsN(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 Listcombination(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); } } }