Wendy Wordsmith likes to do the daily jumble in the newspaper. Wendy has written a program that, given a word, prints all the permutations of that word. Then, Wendy can look through the list and pick out the answer. However, Wendy's computer is old, and has a very short call stack, only five or so frames long.
Wendy has provided her program below. Your task is to update Wendy's program so that it can print all the permutations of any string of arbitrary length.
public class Permuter {
private static void charSwap(char c[], int index1, int index2) {
char c1 = c[index2];
c[index2] = c[index1];
c[index1] = c1;
}
/*
* permute: Print all the permutations to the right of index
* in a character array.
*/
private static void permute(char c[], int index) {
// Base case: simply print the current array
if (c.length - 1 == index) {
java.lang.System.out.println(c);
// Recursive case: find all permutations to the right
// of the current index.
} else {
for(int i = index; i < c.length; i++) {
// swap a character to the right with the current index.
charSwap(c, index, i);
// increase the index and repeat.
permute(c, index + 1);
// get the array back to the starting point.
charSwap(c, i, index);
}
}
}
/*
* permuteString: Print all permutations of a string.
*/
private static void permuteString(String s) {
permute(s.toCharArray(), 0);
}
/*
* Main: Call permuteString() to print all permutations of a string.
*/
public static void main(String[] args) {
if (args.length != 1) {
java.lang.System.out.println("Syntax: java Permuter");
return;
}
permuteString(args[0]);
}
}
Your program should...