Reputation: 11
I know that there are many solutions on the internet for my specific question, but I have been trying to solve it in a specific way and it doesn't work and I really can't understand what is wrong. In my case I simply want to print the permutations. Here is my code:
a = "abc";
function f7(a, b) {
//document.write("str: "+a+" b:"+b+"<br>");
if (b.length == 2) {
perm = b + a;
return perm;
}
var c = [];
var str = [];
for (i = 0; i < a.length; i++) {
c[i] = b + a.charAt(i);
str[i] = a.substring(0, i) + a.substring(i + 1);
document.write("i: " + i + " c[i]: " + c[i] + " str[i]: " + str[i] + "<br>");
return f7(str[i], c[i]);
}
//return {str,c}
}
document.write(f7(a, ""));
//g=f7(a,"");
//document.write(g.str+"<br>");
//document.write(g.c+"<br>");
The above code doesn't go beyond the first permutation, and I can't understand why. Thanks in advance for any advice
Upvotes: 0
Views: 87
Reputation: 8261
Returning value in the loop causes escaping the loop. You are returning the value in for
statement that stops immediately before loop complete.
You can use temporary variable to save value in for loop, and then return it.
a = "abc";
function f7(a, b) {
//document.write("str: "+a+" b:"+b+"<br>");
if (b.length == 2) {
perm = b + a;
return perm;
}
var c = [];
var str = [];
var temp = '';
for (i = 0; i < a.length; i++) {
c[i] = b + a.charAt(i);
str[i] = a.substring(0, i) + a.substring(i + 1);
document.write("i: " + i + " c[i]: " + c[i] + " str[i]: " + str[i] + "<br>");
temp += f7(str[i], c[i]);
}
return temp
}
document.write(f7(a, ""));
//g=f7(a,"");
//document.write(g.str+"<br>");
//document.write(g.c+"<br>");
Upvotes: 1