I am very new to combinatorics. So that is why I am trying to figure out a way to generate all possible combinations for a specific range of numbers. The problem is that I really do not know how it works. I am trying to understand the logic for 2 days now. Every combination should have three numbers, stored in an extra array, for example: [7,4,8]
. The user should be able to choose a range of numbers. I would really appreciate it if somebody could help me.
I was trying to use several for loops to get certain combinations. But that technique seems to be very very complicated and very very unclean. I am struggling with figuring out which possible combination types there can be. I want to write a function that looks like that:
function generateCombinations(min, max) {
// LOGIC
return combinations;
}
generateCombinations(0, 10);
// Example OUTPUT
/*
[
[0,5,10],
[10,10,10],
[7,4,1],
. . .
]
*/
Hopefully you can help me. Thank you
CodePudding user response:
It is very straightforward. Just use 3 nested loops(since your combination is of size 3) that iterate from min to max, keep collecting the combinations in an array and you are done.
function generateCombinations(min, max){
let result = [];
for(let i = min; i <= max; i){
for(let j = min; j <= max; j){
for(let k = min; k <= max; k){
result.push([i, j, k]);
}
}
}
return result;
}
console.log(generateCombinations(0, 10));
CodePudding user response:
Are you looking for combinations between the Arrays so
[7,8,4]
[1,6,0]
[7,1] [7,6] [7,0] [7,1,6] [7,1,0] [7,6,0] [8,1] [8,6] [8,0]
etc.
or should the numbers combine with each other inside the array, so
[7,8,4]
[1,6,0]
[7,8] [7,4] [7,1] [7,6] [7,0] [7,8,1]
etc.