Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

Divya Mary
Greenhorn
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?

nir sharma
Ranch Hand
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
Posts: 3
Thank you Nir, I got it.