1

I tried to write a function that finds all possible permutations given an array of numbers. Here is my code.

var perm = [];
var usedchar = [];

function findAllPermutations(arr) {

  for (var i = 0; i < arr.length; i++) {
    var x = arr.splice(i,1)[0];
    usedchar.push(x);

    if (usedchar.length == 3) {
      perm.push(usedchar);
    }

    findAllPermutations(arr);
    usedchar.pop();
    arr.splice(i,0,x);
  }
}

findAllPermutations([1,2,3]);

console.log(perm); //-> [[],[],[],[],[],[]]

I expect to get:

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Can someone explain why I'm not getting this answer?

5
  • I can't explain because you never labelled your question with the language you are using. Commented Aug 25, 2015 at 1:30
  • @TimBiegeleisen: console.log is a dead giveaway; but OP, you do need to tag questions appropriately (and indent them correctly, or no-one will bother to look for where your scope is). Commented Aug 25, 2015 at 1:33
  • I would assume some flavor of JavaScript, but adding a label also helps people find a question. Commented Aug 25, 2015 at 1:34
  • There is no need to terminate a block with a semicolon, it is seen as an empty statement. Not harmful, just useless. Commented Aug 25, 2015 at 2:43
  • Apologies, this is my second post! Thanks for the feedback, I'll make sure to do so in the future. Commented Aug 25, 2015 at 2:49

2 Answers 2

1

You're using the same array that holds your intermediate result as storage for your algorithm and things are getting mixed up. You need to either separate the two or make sure you clone your usedchar array before pushing it into your perm array. Something like this plunker: http://plnkr.co/edit/HQ6q8fo8S0K21cISQKVt

  var perm = [];
  var usedchar = [];
  var another = [];

  function findAllPermutations(arr) {


  for (var i = 0; i < arr.length; i++) {
    var x = arr.splice(i,1)[0];
    usedchar.push(x);

    if (usedchar.length == 3) {
      perm.push(usedchar.slice());
    };

    findAllPermutations(arr);
    usedchar.pop();
    arr.splice(i,0,x);
  };
};

findAllPermutations([1,2,3]);
console.log(perm);
Sign up to request clarification or add additional context in comments.

2 Comments

Where will the OP find the $ function? Why is it necessary?
You're right, don't need it. That's just from the plunker I used. I'll edit it out.
1
perm.push(usedchar);

needs to be

perm.push(usedchar.slice());

in order to clone the usedchar array, to snapshot it at that moment. Otherwise, you end up with six references to usedchar that had all kinds of stuff pushed in and then popped out, ending up empty at the end.

Comments

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.