简体   繁体   中英

Javascript recursion not functioning as expected

I ported this method from Java to Javascript. With an "original" array with 9 objects in it, the Java code made 3000 subarrays of size 4.

In this javascript code I get 6 subarrays of size 9.

var hitterArray = new Array();

function permute(level, permuted, used, original){

    if (level == 4) {
        hitterArray.push(permuted); //array of arrays
    } else {
        for (i = 0; i < original.length; i++) {
            if (!used[i]) {
                used[i] = true;

                permuted.push(original[i]);

                permute(level + 1, permuted, used, original);

                used[i] = false;
            }
        }
    }
}

I want 3000 subarrays of size 4, why is that not working?

This is how I initialize the permute function:

            var used = new Array(results.length);
            for(p = 0; p < used.length; p++){
                used[p] = false;
            }
            var permuteArray = new Array();

            permute(0, permuteArray, used, results);

Insight appreciated

I think the error is on your for loop, you need to declare the i with var otherwise you make it a global variable.

for(var i = 0; ....

Another thing which might have impact is that you are always passing references to the arrays: used and permuted that is likely to have some impact on the result, consider cloning the arrays with array.slice() to create new copies of them.

And also I think the permutations of 4 objects out of 9 should be 3024 (9*8*7*6), so you should get 3024 arrays of 4

edit

function permute(level, permuted, used, original){

    if (level == 4) {
        hitterArray.push(permuted); //You don't need to create a copy here, but if performance is not an issue, you might want to do it, for clarity
    } else {
        for (var i = 0; i < original.length; i++) {
            if (!used[i]) {
                var newused = used.slice();
                var newpermuted = permuted.slice();

                newused[i] = true;

                newpermuted.push(original[i]);

                permute(level + 1, newpermuted, newused, original);

                //used[i] = false; //this won't be needed as you've just created a copy of the original one
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM