-
sticky recursion problem
there is a recursion example in my text book. it is a bit difficult for me. so i thought i would type it out and follow the progress of the code in the debugger to get a better understanding of how it works. trouble is, i can't figure out what kind of statement in a simple test class will get it working and actually PRINTING out all the permutations.
the example code takes any given word and is supposed to spit out all the permutations of the word. for example, the user defined word might be "key". the program should print out . . .
key
kye
eky
eyk
yke
yek
ordinarily, i wouldn't be so dead set on understanding this example, but it is essential that i do.
the book gives the class that has the recursion interator, but if someone could help me out with a bit of code (i know it must only be a line or two) that will start up the iterator to give me the results.
the code is
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();
}
}
thanks
crq
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks