3

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?

Sarun UK
  • 6,210
  • 7
  • 23
  • 48

1 Answers1

12

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));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Anyway we can do the last one with strings too? As in pass it (["ab","cd","ef"],3) and get abcdef, cdabef, etc? – mplungjan Feb 10 '23 at 10:59
  • @mplungjan That example sounds like you're looking for permutations not combinations, but sure enough `choose` also works with string values (or really anything). Use `choose(["ab","cd","ef","gh"],3).map(c => c.join(''))`. You could build a string-specific version of `choose` as well that uses string concatenation instead of array consing. – Bergi Feb 10 '23 at 14:21
  • Hi I [did find a permutation script](https://stackoverflow.com/a/75410478/295783). Yours only does `[ "AABBCC"]` when given an array of AA,BB,CC – mplungjan Feb 10 '23 at 17:49
  • 1
    @mplungjan Well that's because the OP didn't ask for permutations here… There's lots of [SO threads about permutations](https://stackoverflow.com/q/9960908/1048572), including [some with implementions of mine](https://stackoverflow.com/search?q=user%3A1048572+permutations). – Bergi Feb 10 '23 at 18:36