简体   繁体   中英

Javascript computing permutations - why is my code returning unwanted solution when I don't make a copy of the array?

Below is code for a function that returns all permutations of a given array.

function getAllPerms(s) {
  var perms = [];
  if (s.length === 1) {
    perms.push(s);
    } else {
        for (var i = 0; i < s.length; i++) {
            var sub = s.slice(0);
            sub.splice(i, 1);
            var sp = getAllPerms(sub);
            for (var o = 0; o < sp.length; o++) {
                sp[o].unshift(s[i]);
                perms.push(sp[o]);
            }
        }
    }
    return perms;
  }
  console.log(getAllPerms([1,2]));  // result is [[1, 2], [2, 1]]

however if i don't make a copy of the array and splice the original array I don't get the same output, and I have been racking my brain to understand why? To me, it seems as though it should work either way. Below is the code with changes to the original array.

function getAllPerms(s) {
    var perms = [];
    var len = s.length
    if (s.length === 1) {
        perms.push(s);
    } else {
        for (var i = 0; i < len; i++) {
            var digit = s[i];
            s.splice(i, 1);
            var sp = getAllPerms(s);
            for (var o = 0; o < sp.length; o++) {
                sp[o].unshift(digit);
                perms.push(sp[o]);
            }
        }
    }
    return perms;
}
console.log(getAllPerms([1,2])); // result is [[2, 1], [2, 1]]

For the first set of code I get the correct result,[[1, 2], [2, 1]], but for the second bit of code I get something strange, [[2, 1], [2, 1]]. Cannot for the life of me figure out what is going on.

When you run the code that changes the original array, you're actually modifying the input array s to be first [1,2] then [2,1] , and your return array is just the original array s multiple times, so modifying s to become the second element also modifies it as the first element.

You can see the effect more simply by running the following:

var x = [1,2]
var p = []
p.push(x)
x[0] = 2
x[1] = 1
p.push(x)

Observe how x and p change after each line.

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