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

1

4

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?

Irradiant answered 18/10, 2020 at 15:3 Comment(3)
What's the expected output?Quartis
[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]Irradiant
@YuvalLevental Rather than adding a comment for your expected result, edit your question.Aerodonetics
V
13

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));
Virility answered 18/10, 2020 at 15:9 Comment(4)
Anyway we can do the last one with strings too? As in pass it (["ab","cd","ef"],3) and get abcdef, cdabef, etc?Anthesis
@Anthesis 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.Virility
Hi I did find a permutation script. Yours only does [ "AABBCC"] when given an array of AA,BB,CCAnthesis
@Anthesis Well that's because the OP didn't ask for permutations here… There's lots of SO threads about permutations, including some with implementions of mine.Virility

© 2022 - 2024 — McMap. All rights reserved.