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?

3
  • 1
    What's the expected output? Commented Oct 18, 2020 at 15:04
  • [[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]] Commented Oct 18, 2020 at 15:05
  • @YuvalLevental Rather than adding a comment for your expected result, edit your question. Commented Oct 18, 2020 at 15:13

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

4 Comments

Anyway we can do the last one with strings too? As in pass it (["ab","cd","ef"],3) and get abcdef, cdabef, etc?
@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.
Hi I did find a permutation script. Yours only does [ "AABBCC"] when given an array of AA,BB,CC
@mplungjan 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.