3

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.

1
  • 1
    Make it a function that takes n as a parameter? I don't understand your question. Commented Feb 9, 2019 at 17:12

1 Answer 1

5

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

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

1 Comment

This could work. I'm gonna try to implement this in my application now, thank you for your quick response.

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.