ORESoftware / r2g

▷ Test your package in the published format, without having to publish to NPM.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

solving unrelated issue - bounty

ORESoftware opened this issue · comments

This problem is unrelated to this repo:
https://gist.github.com/ORESoftware/941eabac77cd268c826d9e17ae4886fa

Trying to get the above routine created.

function combine(k, arr, prefix=[]) {
    if(arr.length > k) {
        throw new Error('Not enough elements to combine.');
    }
    if (k == 0) return [prefix];
    return arr.flatMap((v, i) =>
        combine(k-1, arr.slice(i+1), [...prefix, v])
    );
}

interesting technique

function combine(x: number, list: number[]): number[][] {
    if (x === 0) {
        return [[]];
    } else if (x === 1) {
        return list.map(e => [e]);
    } else {
        const combinations: number[][] = [];
        for (let i = 0; i < list.length; i++) {
            for (const subcombination of combine(x - 1, list.slice(i + 1))) {
                combinations.push([list[i], ...subcombination]);
            }
        }
        return combinations;
    }
}