0

I am trying to make an array of all the permutations for a given string using Heap's Algorithm. The function prints the correct array results when I use console.log to test. However, when I try to push all of the arrays into a new array it pushes the same initial array every time.

In this example it pushes [a, a, b] 6 times.

First of all, why is it doing this? Second, how do I get around it and push all of the correct results into my new array.

function permAlone(str) {
//make str into array
var arr = str.split('');
var allArrays = [];
//Heap's Algorithm to make new array with all permutations

var swap = function (array, pos1, pos2) {
    var temp = array[pos1];
    array[pos1] = array[pos2];
    array[pos2] = temp;

};

var permute = function(array, n) {
    n = n || array.length;
    if (n === 1 ) {
        console.log(array);
        //allArrays.push(array);
    }
    else {
        for (var i=1; i <= n; i += 1) {
            permute(array, n-1);
            if (n%2) {
                var j=1;
            }
            else {
                j=i;
            }
            swap(array, j-1, n-1);
        }
    }

};
permute(arr);
//console.log(allArrays);
}

permAlone('aab');
1
  • didn;t pay much attention to your code but it sounds like you need to use a closure. Commented Nov 8, 2016 at 21:37

1 Answer 1

1

You only ever have one array (not counting allArrays), so you've pushed the same array into allArrays six times.

You should make a copy of your array before pushing it. You can do that with slice:

allArrays.push(array.slice(0));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that got it! Since it runs 6 times and array changes each time, I was assuming that it would push the different version of the array into the new array. I still don't quite understand why it doesn't.
@andrewgi Objects (which includes arrays) aren't copied like primitive values are when they are passed or assigned. Try this for instance: var arr1 = []; var arr2=arr1; arr1.push('test'); console.log( arr2 ); You'll see that arr2 and arr1 are literally the same array, so when you log arr2 you see the value test that was pushed into arr1. If you had var arr2=arr1.slice(0); to make a copy instead then you'd have two separate arrays and wouldn't see 'test'.
Ahhh ok I understand now, it's stored permanently and there is no catching a copy or "screenshot" of it when its running through a loop. Thanks!!

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.