0

I am currently trying to find the various permutations of a string. The code used works for strings with 5 characters. But With more than 5, it throws an error -"too much recursion".

function doPerm(str, arr) {

  if (typeof (str) == 'string') 
      str = str.split('');

  if (str.length === 0){
    if(allowedPerm(arr.join('')))  
      permutations.push(arr.join(''));

  }
  for (var i = 0; i < str.length; i++) {

    var x = str.splice(i, 1);
    //console.log(i+"--"+str);
    arr.push(x);
    doPerm(str, arr);
    arr.pop();
    str.splice(i, 0, x);

  }

}
//doPerm("abcde", []);//works returns 120
doPerm("abcdefa", []);

What can I change to avoid this??. And also is there a better way to do it??

leoOrion
  • 1,833
  • 2
  • 26
  • 52
  • This code looks incomplete or i don't understand javascript at all. allowedPerm is defined where? Well, regardless: too much recursion means that your stack is full. This happens all the time with too much recursion (doPerm is calling itself multiple times within a loop -> exponential growth!!!). Sometimes increasing this stack is enough, but in your case this will not help. If 5 are heavy, 10 chars will be overkill. You need to implement an non-recursive algorithm. In general, each well-used programming language should offer some permutation function in the standard library. – sascha May 10 '16 at 16:03
  • allowedPerm is used to reject permutations with consecutive letters in it. See Full code here: https://www.freecodecamp.com/challenges/no-repeats-please# – leoOrion May 10 '16 at 17:09
  • Also js does not have a permutation function. I also checked for non-recursive algorithm to solve the problem. No luck so far – leoOrion May 10 '16 at 17:11
  • What about [this](http://stackoverflow.com/questions/2390954/how-would-you-calculate-all-possible-permutations-of-0-through-n-iteratively)? There is even a js-implementation. – sascha May 10 '16 at 17:20
  • thanks but i found a recursive Alg. that works.:http://stackoverflow.com/questions/9960908/permutations-in-javascript . (The First one)Initially since it also uses recursion and is very similar to my previous code, i thought it would not work. But it did. Still trying to figure out the difference and why... – leoOrion May 10 '16 at 17:28

0 Answers0