Code doubt for a code snippet

for(int i =0 ; i<rrs.length() ; i++) {

  mr.add(rrs.substring(0, i) + cc + rrs.substring(i));

}

suppose “cc” here is ‘a’…and rrs for the time being is ‘bc’…now if rrs.length() is 2,this means the loop shall run for 2 times…but then how come the answer is coming out to be abc,bac,bca which is possible onlyif the loop runs for 3 times

@himanshuep32,
Can you please share the complete code?

package recursionquestions; import java.util.ArrayList; public class Recursion { public static void main(String[] args) { System.out.println(getPermutations(“abc”)); } public static ArrayList getSS(String str){ if(str.length() == 0 ) { ArrayList br = new ArrayList<>(); br.add(" “); return br; } char cc = str.charAt(0); String a = str.substring(1); ArrayList rr = getSS(a); ArrayList mr = new ArrayList<>(); for(int i=0 ; i<rr.size() ; i++) { mr.add(rr.get(i)); mr.add(cc + rr.get(i)); } return mr; } public static ArrayList getPermutations(String str){ if(str.length() == 0) { ArrayList br = new ArrayList<>(); br.add(” "); return br; } char cc = str.charAt(0); String a = str.substring(1); ArrayList mr = new ArrayList<>(); ArrayList rr = getPermutations(a); for(String rrs:rr) { for(int i =0 ; i<rrs.length() ; i++) { mr.add(rrs.substring(0, i) + cc + rrs.substring(i)); } } return mr; } }

@himanshuep32,

	for (String rrs : rr) {
		for (int i = 0; i < rrs.length(); i++) {
			mr.add(rrs.substring(0, i) + cc + rrs.substring(i));
		}
	}

Look at this code. If cc is a, then rr = [bc , cb ]
Now for rrs = bc
when i = 0, mr.add("" + “a” + “bc”) , thus abc will be added to mr.
when i = 1, mr.add(“b” + “a” + “c”), thus bac will be added to mr.
when i=2, mr.add(“bc” + “a” + “”), thus bca will be added to mr.

Here the length of "bc " is 3 because there is a " " char at the end. Hence the loop runs 3 times.

@himanshuep32,
Also, I have corrected your code: https://ide.codingblocks.com/s/209329
Whenever you use Arraylist put the parameter as well. Parameter defines the values it will store. For arraylist of strings use ArrayList

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.