Open VaJoy opened 7 years ago
function cartesian (...lists) {
return lists
.map(list => list.map(item => [item]))
.reduce((listsA, listsB) =>
listsA.reduce((list, listA) =>
list.concat(
listsB.map(listB => listA.concat(listB))
), []
)
)
}
(() => {
function getArranging (...list) {
return build(list)
}
function build (list, result = list.shift()) {
return !list.length ? result : build(list, [].concat(...list.shift().map(item =>
result.map(resultItem =>
[].concat(item, resultItem)
)
)))
}
let a = [0, 1]
let b = [3, 4, 5]
let c = [6, 7]
let ret = getArranging( a, b, c )
console.log(JSON.stringify(ret))
})()
function getArranging(...args: number[][]) {
const result = [];
(function loop(tmp: number[] = []) {
if (tmp.length === args.length) {
result.push(tmp)
return
}
const values = args[tmp.length]
values.forEach(value => {
loop([...tmp, value])
})
})();
return result;
}
console.log(
getArranging([0, 1], [3, 4, 5], [6, 7])
);
function getArranging(...list){ //TODO - 返回参数的排列组合 return list.reduce((result, curr, listIndex) => { curr.forEach((item, index) => { let insertCount = len(list)/curr.length; let interval = len(list.slice(listIndex)); let sufixLen = len(list.slice(listIndex + 1)); let startPosition = index sufixLen; Array.from(new Array(insertCount)).forEach((_item, _index) => { let round = (Math.ceil((_index + 1) / sufixLen) - 1) interval; position = startPosition + ((_index % sufixLen == 0 || !sufixLen) ? round : round + _index % sufixLen); result[position] = result[position] || []; result[position][listIndex] = item; }); }); return result; }, []); } function len(list) { return list.reduce((result, curr) => { result *= curr.length; return result; }, 1); } var a = [0, 1]; var b = [3, 4, 5]; var c = [6, 7]; var d = [8, 9, 10] var ret = getArranging( a, b, c, d ); console.log(ret);
有这么几个变量:
a
其值可能为 0、1b
其值可能为 3、4、5c
其值可能为 6、7实现一个函数
getArranging
可以返回它们的可能值的排列组合二维数组: