Saturday, January 2, 2010

A string Permutations

This might be a good example of recursion.

So one example question would be:
Print all permutations of a given string. (i.e. "abc" would print "abc", "acb", "bac", "bca", "cab", and "cba")

I start thinking about patterns in terms of recursion.

1. There should be a base case and a recursive case.
2. For recursive case, I need to call the same function with sub version of original string.
3. Let's call the function name "printPermutation()".
4. The pattern I came up with is the following
  • Go through the String from index 0 to index length -1
  • And then take the character at index i and call printPermutation() with rest of the string
  • Let's take a look at example string "abc"
  • My logic is when index is at 'a' and call printPermutation() with "bc" and when index is at 'b' call printPermuation() with "ac" and so on.
  • So the string will eventually become size of 1 then print all and return (this seems like base case)
  • Then when the function takes size of 1 string, it needs to know what is the parent string is.(sort of path the function is taken)
  • OK... So I wrote printPermutation() with two parameters: printPermutation(String current, String parent);
5. Now I have the base case:

if(current.length() == 1){

System.out.println(parent+current);

return;

}

6. Oh now, I need a simple function takes an index and a string. It will remove the character(index) from given string.

public static String removeCharAt(int index, String str) {
return str.substring(0, index) + str.substring(index + 1);
}

7. then recursive part would look like

for(int i =0; i<current.length(); i++)
printPermutation(removeCharAt(i, current), parent + current.charAt(i));
}

8. Following is my solution

public static void printPermutation(String current, String parent){
if(current.length() == 1){
System.out.println(parent+current);
return;
}

for(int i =0; i printPermutation(removeCharAt(i, current), parent + current.charAt(i));
}

}

public static String removeCharAt(int index, String str) {
return str.substring(0, index) + str.substring(index + 1);
}


What do you think?