[英]Can you return n choose k combinations in Javascript using Array.flatMap?
For instance, this is 5 choose 2:例如,这是 5 选择 2:
var array = [0,1,2,3,4]; var result = array.flatMap( (v, i) => array.slice(i+1).map(w => [v, w]) ); console.log(result);
How would I be able to do 5 choose 3 using this method?我怎样才能使用这种方法做 5 选择 3?
Just add another level of nesting:只需添加另一层嵌套:
var array = [0,1,2,3,4];
var result = array.flatMap((v, i) =>
array.slice(i+1).flatMap((w, j) =>
array.slice(i+1+j+1).map(u =>
[v, w, u]
)
)
);
console.log(result);
At this point, it might be easier to do with recursion though:在这一点上,使用递归可能更容易:
function choose(arr, k, prefix=[]) { if (k == 0) return [prefix]; return arr.flatMap((v, i) => choose(arr.slice(i+1), k-1, [...prefix, v]) ); } console.log(choose([0,1,2,3,4], 3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.