【问题标题】:Why isn't this function to return all permutations of a given array working?为什么这个函数不能返回给定数组的所有排列?
【发布时间】: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


【解决方案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]) );

我不确定这样做的目的是什么,但它就像某种代码测试一样让我很感兴趣,所以我试图解决它。

【讨论】:

  • 如果您正在寻找一个优雅的解决方案,也许像 this?
【解决方案2】:

This answer is the most elegant solution I found.

const permutator = (inputArr) => {
  let result = [];

  const permute = (arr, m = []) => {
    if (arr.length === 0) {
      result.push(m)
    } else {
      for (let i = 0; i < arr.length; i++) {
        let curr = arr.slice();
        let next = curr.splice(i, 1);
        permute(curr.slice(), m.concat(next))
      }
    }
  }

  permute(inputArr)

  return result;
}

console.log(permutator([1,2,3]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多