Generating all permutations of a certain length

In order to pick five characters from a string recursively, follow a simple algorithm:

  • Your method should get a portion filled in so far, and the first position in the five-character permutation that needs a character
  • If the first position that needs a character is above five, you are done; print the combination that you have so far, and return
  • Otherwise, put each character into the current position in the permutation, and make a recursive call

This is a lot shorter in Java:

private static void permutation(char[] perm, int pos, String str) {
    if (pos == perm.length) {
        System.out.println(new String(perm));
    } else {
        for (int i = 0 ; i < str.length() ; i++) {
            perm[pos] = str.charAt(i);
            permutation(perm, pos+1, str);
        }
    }
}

The caller controls the desired length of permutation by changing the number of elements in perm:

char[] perm = new char[5];
permutation(perm, 0, "abcdefghiklimnop");

Demo.

Leave a Comment