I've been working through an example in a book that shows you how to permute a String into all it's possible combinations, but as I'm still quite a beginner at programming in general, I can't actually understand how the code works!
Could someone please analyze the code I've supplied and give me a thorough explanation of what everything does and how it does it?
Many thanks,
Alex.
class PermuteString{
String word;
int index;
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();
}
}
public class PermuteStringDemo {
public static void main(String[] args){
PermuteString p = new PermuteString("opyn");
while(p.morePermutations())
System.out.println(p.nextPermutation());
}
}