-4

I have been trying to understand how this works, but due to my limited knowldge of java, I fail to. Here is the code which will produce permutations:

private static void permutation(String prefix, String str) {
    int n = str.length();

    if (n == 0) System.out.println(prefix);

    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

//main:

public static void main(String[] args) {
        permutation("","ab");
    }

I tried to look at many stackoverflow posts but they dont go over the basics on how this works

Community
  • 1
  • 1
aadr darf
  • 1
  • 1
  • possible duplicate of [Generating all permutations of a given string](http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string) – Rakesh KR Nov 03 '14 at 17:55
  • 1
    Here's a hint: in the call to `permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));`, don't try to think so much about the code path beyond that method call. Instead, imagine that it was a completely different function, that printed `prefix`, and after that, all of the permutations of `str`. – Sam I am says Reinstate Monica Nov 03 '14 at 17:58

3 Answers3

2

The idea of this method is to use recursion to find all the permutations of a string. In order for recursion to work, it has to define the problem in terms of the same problem, slightly reduced.

What are the permutations of a string? Let's look at an example for the string "abc":

abc
acb
bac
bca
cab
cba

What we note about this is that the permutation is like picking one of the letters to be first, and then doing the same thing for the rest. That is, if we pick 'a' to be first, we have the permutations:

bc
cb

If we pick 'b' to be first, we have

ac
ca

And if we pick 'c', we have

ab
ba

So we can define our problem in terms of itself (reduced). So to permute a string that has n characters, we need to pick each of these characters, decide that it is the first, and then attach all the permutations of the remaining string to this first letter. This means we have to find all the permutations of a string that is n-1 characters long, and append it to the first letter we chose.

So,

  • To find the permutations of an n-character string:
  • Loop through all the characters of the string
    • Pick the current character we're looking at as the first character
    • Get all the remaining characters as a string (the length is now n-1)
    • Find all the (n-1)-character string's permutations
    • Append each of them to the character we picked as first.

But when do we stop? We stop when we get to an empty string, because it has no permutations.

What your program does is exactly this, but since it wants just to print the permutations, not to collect them, what it does is keep all the choices of first letters done in upper levels of the recursion. These are handed over from the upper levels of the recursion. This way, when we get down to an empty string, the prefix contains a particular series of choices of first letters. Since there is nothing more to permute, we can just print what we got.

When we return from the recursion at any level, the current level knows that all the permutations with the current choice of first character have been printed. So it moves to the next first character, and again, passes all the choices so far down. Again, all the levels under it will add their first letters until the string is empty.

At the top level you have to call it with an empty prefix, because of course, you haven't made any first character choices at this point. Let's see what happens if we call permutation("","abc"):

  • Level 1 picks a, calls permutation("a","bc")
    • Level 2 picks b, calls permutation( "ab","c")
      • Level 3 picks c, calls permutation( "abc", "" )
        • Level 4 has an empty string, so it prints abc
      • Level 3 has nothing more to choose.
    • Level 2 picks c, calls permutation( "ac", "b")
      • Level 3 picks b, calls permutation( "acb", "" )
        • Level 4 has an empty string, so it prints acb
      • Level 3 has nothing more to choose
    • Level 2 has nothing more to choose
  • Level 1 picks b, calls permutation("b","ac")
    • Level 2 picks a, calls permutation("ba","c")
      • Level 3 picks c, calls permutation( "bac", "" )
        • Level 4 has an empty string, so it prints bac
      • Level 3 has nothing more to choose
    • Level 2 picks c, calls permutation("bc","a")
      • Level 3 picks a, calls permutation( "bca", "" )
        • Level 4 has an empty string, so it prints bca
      • Level 3 has nothing more to choose
    • Level 2 has nothing more to choose
  • Level 1 picks c, calls permutation("c","ab")
    • Level 2 picks a, calls permutation("ca","b")
      • Level 3 picks b, calls permutation( "cab", "" )
        • Level 4 has an empty string, so it prints cab
      • Level 3 has nothing more to choose
    • Level 2 picks b, calls permutation("cb","a")
      • Level 3 picks a, calls permutation( "cba", "" )
        • Level 4 has an empty string, so it prints cba
      • Level 3 has nothing more to choose
    • Level 2 has nothing more to choose
  • Level 1 has nothing more to choose
RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • i dont understand •Level 2 picks c, calls permutation( "ac", "b") , can you explain why it would permutate like that ? – aadr darf Nov 04 '14 at 15:25
  • Suppose you are at that level. You have the prefix from the parent, which is "a". You have the string to permute "bc". You have already picked "b" as first letter, and all the permutations that begin with "ab" were handled already. So what's the next "first letter" you pick from "bc"? You only have "c" left. And when you remove it, you have only "b" to permute. So this is what you pass to the next level. – RealSkeptic Nov 04 '14 at 15:36
  • ok understand now. As I got down the list, I dont understand this one: Level 1 picks b, calls permutation("b","ac") – aadr darf Nov 04 '14 at 16:07
  • It's the same thing. At this level, you have just "" from the parent, and you have "abc" to permute. You have already picked "a" as your first letter, and all the permutations beginning with "a" are complete. Now you pick "b" as your first letter. The remaining string is "ac". And that's what you pass to the next level. Maybe you should write down what each level has at the moment and you'll be able to follow it better. – RealSkeptic Nov 04 '14 at 16:20
  • ok i am slowly understanding this, however I dont understand what yo mean when you wrote: Level 2 has nothing more to choose(look at the first time u wrote that) – aadr darf Nov 04 '14 at 17:35
  • Once again, what does Level 2 do? Its parameters are "a" and "bc". It has already picked "b" as first letter, and "c" as first letter. So it has no more letters to choose. At this point, this level is finished and control returns to level1. – RealSkeptic Nov 04 '14 at 17:44
0

The idea is pretty simple.

  1. permutation will print each of the permutations of str preceded by prefix.
  2. If str is empty, the only thing to print is prefix itself.
  3. If it isn't empty, then we can break the problem up into a set of subproblems, each with a slightly longer prefix & shorter str by moving a different character form str to the end of prefix, and printing all of the permutations of each of these combinations. (Since we stop the recursion when str is empty, this gets us closer to that happening.)

Note that, if there are any duplicate characters, there will be duplicates in the result.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

permutation is a recursive function, which means that it is a method that calls itself. Because we don't want the method to run forever in a continuous loop, we need to provide a base case which means a condition that causes the method to exit without calling itself. These methods are easier to understand by just following along with sample values. For instance, if we try permutation("", "a"), the code will run in this order (n is the length of str):

permutation("", "a")// n=1 so loop through "a" 
==>permution("a", "")// n=0 so print prefix "a" and exit

Now try permutation("", "ab"), we will have:

permutation("", "ab")// n=2 so loop through "ab"
==>permutation("a", "b")// n=1 so loop through "b"
====>permution("ab", "")// n=0 print prefix "ab" and exit
==>permutation("b", "a")// n=1 so loop through "a"
====>permution("ba", "")// n=0 print prefix "ba" and exit