Generate list of possible combinations

Asked

Viewed 3,615 times

10

We have 4 teams:

Time 1 | Time 2 | Time 3 | Time 4

I would like to know how to automatically build a list of possible combinations of games between these teams.

Example:

Time 1 x Time 2 | Time 1 x Time 3 | Time 1 x Time 4 | ...

I’m having problems with the logic for the application.

1 answer

11


To count the games, you need to make a simple combination:

function combinacaoSimples(n, p) {
    return (fatorial(n) / (fatorial(p) * fatorial(n-p)));
}

function fatorial(n) {
    if(n === 0 || n === 1) {
        return 1;
    }
    for(var i = n; i > 0; --i) {
        n *= i;
    }
    return n;
}

combinacaoSimples(4, 2);

For a list of possible combinations:

var i, j, x = [ "Time 1", "Time 2", "Time 3", "Time 4" ],
    combinations = [];
for(i = 0; i < x.length; ++i) {
    for(j = i + 1; j < x.length; ++j) {
        combinations.push([ x[i], x[j] ]);
    }
}
  • This result also got as follows: $n = 4;&#xA;console.log($n*($n-1)/2);, what I need to create the listing, as follows: Time 1 x Time 2 Time 2 x Time 3 Time 1 x Time 3 Time 3 x Time 4 ;...

  • I thought you wanted the number of possible combinations. I edited the answer with the code to get the list of combinations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.