Severin Paar
Severin Paar

Reputation: 78

Dynamic number of nested loops (in Javascript)

I want to generate every possible combination of numbers, with n beeing the highest.

Eg:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

My current approach to this is pretty simple, just n for loops.
The problem with this is, that I don't know n.

n = 3;
for (a=0; a <= n; a++) {
    for (b=0; b <= n; b++) {
        for (c=0; c <= n; c++) {
            console.log(`${a} ${b} ${c}`);
        }
    }
}

I need a way of generating these loop dynamically.



Any other approach for generating all possibilities is also welcome.

Upvotes: 3

Views: 593

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take a function for a cartesian product, an array of the wanted signs and the wanted length and return this result.

function getCombinations(signs, length) {
    const cartesian = array => array
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
    
    return cartesian(Array.from({ length }, _ => signs));
}

console.log(getCombinations([1, 2, 3], 5).map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 5

Related Questions