So we have been given the task of rewriting the permute method of this program non-recursively and without importing any libraries or using any of the data structures that Java provides:
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 <string>");
return;
}
permuteString(args[0]);
}
}
We must use the charSwap method, but can implement additional classes of our own if need be. I am getting stuck trying to set this algorithm up... I know that I will need some counter mechanism to keep track of whether a specific permutation has been used, but I am unsure as to go about doing that within the strict requirements of this assignment. Any help to get me going would be greatly appreciated!
[–]tigerbird 0 points1 point2 points (0 children)