GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Please help me understand this word generator. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Please help me understand this word generator." Watch "Please help me understand this word generator." New topic
Author

Please help me understand this word generator.

Divya Mary
Greenhorn

Joined: Sep 17, 2012
Posts: 3
The code below generates different permutations of the letters a,b and c with length ranging from 2 to 5. I am not able to understand how the 'return' in the generate method works. My understanding is- Initially we have 'a', then 'aa'. Since its length is 2, return back to the calling method... n becomes 1? and then iterate till the end of alphabets array?
After aa, ab, ac are gernerated n becomes 0. I cant figure out how n becomes 0 and how the next set of words ba, bb and so on are generated. How did the array index point to b?
Can somebody please help me understand?



nir sharma
Ranch Hand

Joined: Sep 11, 2012
Posts: 72

well its quite difficult to convey what exactly is happening because the generate method call itself twice but i will try.
firstly generate(sb, 0, alphabets); is called from the main method and length is 2. Control will come back to this method only after printing 9 combinations with length 2.
Inside generate method, (this is first call)
n=0 and sb.length() = 2
inside for loop


Inside generate method, (this is second call)
n=1 and sb.length() = 2
inside for loop


Inside generate method, (this is third call)
n=2 and sb.length() = 2
so here aa will be printed and control returns to second call and value of sb changes to ab and the ac.
after this control returns to the first call where
inside for loop

and the same procedure follows.

well its quite long explanation, hope you understand. Also you can debug this and see the values and how they change.
Divya Mary
Greenhorn

Joined: Sep 17, 2012
Posts: 3
Thank you Nir, I got it.
 
GeeCON Prague 2014
 
subject: Please help me understand this word generator.