Can you return n choose k combinations in Javascript using Array.flatMap?

我只是一个虾纸丫 提交于 2021-02-19 04:46:13

问题


For instance, this is 5 choose 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?


回答1:


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));


来源:https://stackoverflow.com/questions/64414816/can-you-return-n-choose-k-combinations-in-javascript-using-array-flatmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!