【发布时间】:2020-07-14 19:14:25
【问题描述】:
我正在尝试编写一个函数,该函数将返回给定数字数组的所有排列,如下例所示:
a = [1, 1, 2]
permutator(a) = [
[1,1,2],
[1,2,1],
[2,1,1]
]
b = [2, 3, 4]
permutator(b) = [
[2,3,4],
[2,4,3],
[3,2,4],
[3,4,2],
[4,2,3],
[4,3,2]
]
结果的顺序不准确
您能解释一下为什么下面的代码不起作用吗?我尝试调试,我认为变量 temp 和 result 没有作为数组保存在内存中,但我不确定是否是这种情况以及如何解决它.
permutator = (array) => {
const result = [];
array.forEach((num, i) => {
array.forEach((num2, j) => {
if (i !== j) {
let temp = array;
temp[i] = temp[j];
temp[j] = num;
console.log(`temp: ${temp}`);
console.log(`result: ${result}`);
if (!result.includes(temp)) result.push(temp);
console.log(`result: ${result}`);
}
});
});
return result;
}
如你所见,我尝试了 console.logging 一切都无济于事...
【问题讨论】:
-
请使用
debugger关键字而不是console.log并观看一些有关如何使用debugger关键字调试 javascript 代码的视频? -
我使用 VS Code 进行调试,所以 console.log 只是我绝望地想看看发生了什么,但还是谢谢!
-
a) 数组是通过引用分配的。如果您希望复制,you need to do it explicitly b)
result.includes(temp)也会通过引用比较result元素 c) 这看起来根本不像用于创建排列的算法 -
谢谢@Bergi!只需更改这行代码:“let temp = array;” “让 temp = array.slice();”使算法工作。如果你有时间,你能给我解释一下为什么它看起来不像是一种创建排列的算法吗?我想这不是最有效的,但它确实有效。
-
@MarcosCannabrava 我猜它只适用于长度为 3 的数组。对于一般解决方案,您通常会使用递归。有关解决方案,请参阅this topic。
标签: javascript arrays node.js scope permutation