简体   繁体   English

您可以使用 Array.flatMap 在 Javascript 中返回 n 个选择 k 个组合吗?

[英]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.

相关问题 通过 if 条件从 `Array.flatMap()` 中不返回任何元素 - Return no element from `Array.flatMap()` by if condition 将计数器添加到 javascript 数组的 n 个组合中 - add counter to the n combinations of javascript array 组合问题 - 给定两个整数 n 和 k,编写一个程序以返回 1 2 3 n 中 k 个数字的所有可能组合 - Combination problem - Given two integers n and k, write a program to return all possible combinations of k numbers out of 1 2 3 n Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数) - Javascript - flatMap method over array - (flatMap is not a function) 为什么将 flatMap 与异步 function 一起使用不返回展平数组? - Why does using flatMap with an async function not return a flatten array? 如何使用递归返回 N 个硬币翻转的所有组合? - How to return all combinations of N coin flips using recursion? m个单词数组中n个单词的组合 - Javascript - Combinations of n words from array of m words - Javascript 使用平面图用逗号分隔数组 - using flatmap to separate array with comma 如何在 JavaScript 中的 flatMap 数组方法中获取累加器(flatmap vs reduce)? - How to get accumulator in flatMap array methode in JavaScript(flatmap vs reduce)? 如何选择数组[0]并使用javascript使其成为链接 - How to choose array [0] and make it a link using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM