如果不以相同的顺序使用itertools npm包,如何获得类似于python itertools的数值数组的所有可能组合?
这是一个python实现
from itertools import combinations
input = [0,1,2,3]
output = sum([list(map(list, combinations(input, i))) for i in range(len(input) + 1)], [])
>>> output
[[],
[0],
[1],
[2],
[3],
[0, 1],
[0, 2],
[0, 3],
[1, 2],
[1, 3],
[2, 3],
[0, 1, 2],
[0, 1, 3],
[0, 2, 3],
[1, 2, 3],
[0, 1, 2, 3]]
此函数将返回与问题中所述相似的结果,并对子集和完整数组进行排序。
How to find all subsets of a set in JavaScript?中的getAllSubsets函数
function getUniqueSortedCombinations(inputArray){
const getAllSubsets = theArray => theArray.reduce((subsets, value) => subsets.concat(subsets.map(set => [...set,value])),[[]]);
let subset = getAllSubsets(inputArray)
subset.sort((a, b) => a.length - b.length || String(a).localeCompare(String(b)))
return subset
}
console.log(getUniqueSortedCombinations([0,1,2,3]))