[英]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]]. 对于第一组代码,我得到正确的结果,[[1,2],[2,1]],但是对于第二部分代码,我得到了奇怪的结果,[[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. 当您运行更改原始数组的代码时,实际上是将输入数组s
修改为首先[1,2]
然后是[2,1]
,而返回数组只是原始数组s
多次,因此修改成为第二个元素的s
也会将其修改为第一个元素。
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. 观察每行之后x
和p
变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.