|
posted this yesterday looking for a way to test this. got that done and i have been trying to follow it step by step in the debugger, but i STILL don't get it. can't figure out how this thing works. i have an assignment that wil use something similar to this example so i really need to understand it.
i am getting hung up in the recursive part of the nextPermutation() method . . . specifically that first "else" statement.
String r = word.charAt(index) + substringGenerator.nextPermutation();
if the word is "tocs" then String r = t + substringGenerator.nextPermutation().
but what is the value of substringGenerator.nextPermutation() at that point?
ah, who am i kidding? i have been looking at this thing for hours and hours spread out over 3 days. i just don't get it. could someone have mercy on me and draw me a picture?
public class PermuteString {
private String word;
private int index;
private PermuteString substringGenerator;
public PermuteString(String s) {
word = s;
index = 0;
if (s.length() >1) {
substringGenerator = new PermuteString(s.substring(1));
}
}
public String nextPermutation() {
if (word.length() == 1) {
++index;
return word;
}
else {
String r = word.charAt(index) +
substringGenerator.nextPermutation();
if (!substringGenerator.morePermutations()) {
++index;
if (index < word.length ()) {
String tailString = word.substring(0, index) +
word.substring(index + 1);
substringGenerator = new PermuteString(tailString);
}
}
return r;
}
}
public boolean morePermutations() {
return index < word.length();
}
}
|