无重复且固定长度的数组排列

Ans*_*llC 3 javascript arrays

我无法弄清楚如何生成值的组合。

鉴于:

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)

任何帮助将不胜感激。

Nin*_*olz 5

您可以采取直接的方法并迭代数组,并通过考虑所需的长度来获取其余数组的部分。

function perm(array, length) {
    return array.flatMap((v, i) => length > 1
        ? perm(array.slice(i + 1), length - 1).map(w => [v, ...w])
        : [[v]]
    );
}

perm(['a', 'b', 'c', 'd', 'e'], 3).forEach(a => console.log(...a));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)