0

I am trying to write a code to create permutations of a string. This is my code:

function perm(str){
function addNew(arr,char){
    var result =[];
    for(i=0;i<=arr.length;i++){
      var temp =[...arr];
      temp.splice(i,0,char);
      result.push(temp);
    }
    return result;
  }

  var chars =str.split("");
  var results =[[]];
  for(i=0;i<chars.length;i++){
   var temp =[...results];
   results =[];
   for(j=0;j<temp.length;j++){
     results =[...results,...addNew(temp[j],chars[i])];
   } 

  }

  return results;
}  

perm("abcd")

This returns:

[ [ 'd', 'c', 'a' ],
  [ 'c', 'd', 'a' ],
  [ 'c', 'a', 'd' ],
  [ 'd', 'a', 'c' ],
  [ 'a', 'd', 'c' ],
  [ 'a', 'c', 'd' ] ]

perm(acde) returns:

[ [ 'e', 'd', 'a' ],
  [ 'd', 'e', 'a' ],
  [ 'd', 'a', 'e' ],
  [ 'e', 'a', 'd' ],
  [ 'a', 'e', 'd' ],
  [ 'a', 'd', 'e' ] ]

So, basically the loop is skipping over (only)the second character in the string. Can someone explain why?

P.S. I know the algorithm is pretty inefficient for the problem but I am just starting with coding, and yet to completely understand Heap's algorithm. I am very curious about this behavior though, and would be pretty thankful if someone would explain.

pc12
  • 23
  • 6
  • 3
    Side note: `for(i=0;i<=arr.length;i++){` That should be `<`, not `<=`. – T.J. Crowder Jan 17 '18 at 14:53
  • 3
    Not sure if this is the only issue here, but always use `for (var i` instead of `for (i`, it is causing issues with a variable used for two different loops (and calling one-another). – kLabz Jan 17 '18 at 14:54
  • Hi kLabz, that worked..Thanks! I thought that would get handled by block scope. But I still don't understand why it would just skip a particular index-Do you know that? – pc12 Jan 17 '18 at 15:00

0 Answers0