为什么这个函数不返回给定数组的所有排列工作?

问题描述 投票:1回答:1

我正在尝试编写一个函数,该函数将返回给定数字数组的所有排列,如下例所示:

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和结果没有作为数组保留在内存中,但我不确定是否是这种情况,也不确定如何解决它。

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.loging一切都没有用...

javascript arrays node.js scope permutation
1个回答
1
投票
这适用于三位数,但我不会称呼它为优雅:

let indexAtEachPosition = function (ind, arr) { let arrayGroup = []; let arrLength = arr.length; let movedArray = [...arr]; for (let indx = 0; indx < arrLength; indx++) { let firstItem = movedArray[0]; let otherItems = movedArray.slice(1); otherItems[arrLength - 1] = firstItem movedArray = [...otherItems]; arrayGroup.push(movedArray.join(" ")); } return arrayGroup; } let permutator = function permutator(values) { let returnValue = new Set(); let digitCount = values.length; returnValue.add(values.join(" ")); values.forEach(digit => { indexAtEachPosition(digit, values).forEach(variation => { returnValue.add(variation); }); }); [...values.reverse()].forEach(digit => { indexAtEachPosition(digit, values).forEach(variation => { returnValue.add(variation); }); }); return [...returnValue].map(eachArr => { return eachArr.split(" "); }); }; // console.log( permutator([0,0,0]) ); // console.log( permutator([1,0,0]) ); // console.log( permutator([1,2,3]) ); console.log( permutator([1,1,2]) ); console.log( permutator([2,3,4]) );
© www.soinside.com 2019 - 2024. All rights reserved.