Generate list of possible combinations

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 match combinations between these teams.

Example:

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

I'm having problems with logic for the application.

    
asked by anonymous 02.03.2014 / 06:16

1 answer

10

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] ]);
    }
}
    
02.03.2014 / 06:41