0

I'm trying to make a function that makes an array of all the possible permutations without repetition of the chars in a given array. The problem is that when the recursive call of recur() is made, the rest of the for loop is not executed and as a result the var total consists of 1 string.

   function recur(arr,wordArr) {
    if(arr.length == 0) {
      total.push(wordArr);
    } else {
        for(var i = 0;i < arr.length;i++) {
          var temp = arr;
          var newwordArr = wordArr;
          newwordArr += temp.splice(i, 1);
          recur(temp,newwordArr);
        }
    }
  }



  var arr = "abc".split("");
  var total = [];
  recur(arr,'');
  console.log(total);

Calling recur([a,b],'') should make total = ['ab','ba']

There is something I'm not seeing or what I'm trying to do is simply not allowed. Couldn't find the answer to this even tought I did a lot of searching.

2
  • I've deleted my answer because it wasn't sufficient for what you need, but here is a SO question that does what you're trying to do. Check it out and see if you can replicate the results/adapt your code. Commented Jul 19, 2017 at 4:56
  • @Kevin thanks for the help! Commented Jul 19, 2017 at 5:24

1 Answer 1

1

You need to copy your array in each step of for loop

function recur(arr,wordArr) {
if(arr.length == 0) {
  total.push(wordArr);
} else {
    for(var i = 0;i < arr.length;i++) {
      var temp = Array.from(arr);
      var newwordArr = wordArr;
      newwordArr += temp.splice(i, 1);
      recur(temp,newwordArr);
    }
}
}

Because in JS, all objects are referances, and writing var temp = arr; it will not create new array, it just will create reference to old array arr.

Array.from(oldArray|oldSet)

this function will create new Array and fill with old.

Read more about

Sign up to request clarification or add additional context in comments.

1 Comment

I was hoping for it to be this kind of problem. Thanks a lot!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.