我正在尝试编写一个执行以下操作的函数:
下面的函数(我在网上找到)通过将一个字符串作为参数,然后返回该字符串的所有排列来完成此操作
我无法弄清楚如何修改它以使其与整数数组一起使用(我认为这与某些方法在字符串上的工作方式不同于它们在整数上的工作方式有关,但我不确定. ..)
var permArr = [], usedChars = [];
function permute(input) {
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
ch = chars.splice(i, 1);
usedChars.push(ch);
if (chars.length == 0)
permArr[permArr.length] = usedChars.join("");
permute(chars.join(""));
chars.splice(i, 0, ch);
usedChars.pop();
}
return permArr
};
Run Code Online (Sandbox Code Playgroud)
注意:我希望使函数返回整数数组,而不是字符串数组.
我真的需要使用JavaScript的解决方案.我已经在python中找到了如何做到这一点
我无法弄清楚如何生成值的组合。
鉴于:
const items = ['a', 'b', 'c', 'd', 'e'];
Run Code Online (Sandbox Code Playgroud)
应该生成:
[
['a', 'b', 'c'],
['a', 'b', 'd'],
['a', 'b', 'e'],
['a', 'c', 'd'],
['a', 'c', 'e'],
['a', 'd', 'e'],
['b', 'c', 'd'],
['b', 'c', 'e'],
['c', 'd', 'e']
]
Run Code Online (Sandbox Code Playgroud)
它为数组中的所有项目生成唯一的组合。基本上,每个项目的数组长度是Math.round(items.length / 2)。
任何帮助将不胜感激。
我正在编写一个函数来创建具有最大长度限制的所有可能的排列,并且数组中的每个项目只能使用一次。
原排列代码如下:
function permutations(list)
{
// Empty list has one permutation
if (list.length == 0)
return [[]];
let result = [];
for (let i=0; i<list.length; i++)
{
// Clone list (kind of)
let copy = Object.create(list);
// Cut one element from list
let head = copy.splice(i, 1);
// Permute rest of list
let rest = permutations(copy);
// Add head to each permutation of rest of list
for (let j=0; j<rest.length; j++)
{
let next = head.concat(rest[j]);
result.push(next);
}
}
return …Run Code Online (Sandbox Code Playgroud)