Skip to content

Instantly share code, notes, and snippets.

@ORESoftware
Created October 29, 2022 15:15
Show Gist options
  • Save ORESoftware/941eabac77cd268c826d9e17ae4886fa to your computer and use it in GitHub Desktop.
Save ORESoftware/941eabac77cd268c826d9e17ae4886fa to your computer and use it in GitHub Desktop.
trying to generate combinations of a list

Desired output of a routine:

List with 3 elements

combine(0,[1,2,3]) => [[]] // as  N choose 0 = 1
combine(1,[1,2,3]) => [[1],[2],[3]] // as  N choose 1 = N
combine(2,[1,2,3]) => [[1,2],[1,3],[2,3]]]] // as  N choose N-1 = N
combine(3,[1,2,3]) => [[1,2,3]] // as  N choose N = 1

List with 4 elements

combine(0,[1,2,3,4]) => [[]] // as  N choose 0 = 1
combine(1,[1,2,3,4]) => [[1],[2],[3],[4]] // as  N choose 1 = N
combine(2,[1,2,3,4]) => [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]]] // as 4 choose 2 = 6
combine(3,[1,2,3,4]) => [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] // as  N choose N-1 = N
combine(4,[1,2,3,4]) => [[1,2,3,4]] // as  N choose N = 1

Here is my best take for now (it's close but wrong):

const combine = (x, list) => {

    if(list.length < x){
        throw new Error('not enough elements to combine.');
    }

    if(list.length < 1){
        return [];
    }

    if (x === 0) {
        return list.slice(0)
    }

    const ret = [];

    for(let v of combine(x-1, list.slice(1))){
        ret.push([list[0], ...v]);
    }

    return ret;
}
@ersin-demirtas
Copy link

Have a look at the answer on stackoverflow its a perfect match to what you are trying to do. https://stackoverflow.com/questions/64414816/can-you-return-n-choose-k-combinations-in-javascript-using-array-flatmap/64414875#64414875.

Even with the conditions above you are getting "Uncaught TypeError: v is not iterable"

@Droidking18
Copy link

Droidking18 commented Nov 1, 2022


const combine = (x, list) => {

    if (x === 0) {
        return [[]];
    }

    if (x > list.length) {
        return [];
    }

    if (x === 1) {
        return list.map((element) => [element]);
    }

    if (x > 1) {
        return combine(x - 1, list.slice(1))
            .map((element) => [list[0], ...element])
            .concat(combine(x, list.slice(1)));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment