Search code examples
phpalgorithmfixtures

Is there any algorithm to make round robin schedule having each round unique combinations?


Suppose I have an array of 10 participants [1,2,3,4,5,6,7,8,9,10]

Assuming a league, as there are 10 participants, so each participant will have 9 matches with other 9 participants.

Therefore, there will be 9 rounds having single matches for each participant. For example-

Round 1: 1-2, 3-4, 5-6, 7-8, 9-10 [no repeat for any participant]

Round 2: 1-3, 2-4, 5-7, 8-9, 6-10 [no repeat for any participant]

and so on..

Is there any mathematical algorithmic solution/pattern there?

I would like to avoid array push/pop method if possible.


Solution

  • Yes, there is rather simple algorithm to generate all possible pairs ((N-1)*N/2)
    Put items into two rows.
    At every round player from the top row plays with corresponding player from bottom row.
    Fix the first one.
    Shift all others in cyclic manner.

    Note that you can work with indexes of array, not changing it's contents

    A  B
    D  C
    pairs A-D, B-C
    
    A  D
    C  B
    pairs A-C, D-B
    
    A  C
    B  D
    pairs A-B, C-D
    

    My naive implementation in PHP (ideone) outputs indexes of players:

    function GenPairs($N) {
        for ($i=0; $i<$N-1;$i++){
            echo(0).":";
            echo($N - 1 - $i)."\n";
            for ($j=1; $j<$N/2;$j++){
                echo(1 + (($N - $i + $j - 2) % ($N - 1))).":";
                echo(1 + ((2*$N - $i - $j - 3) % ($N - 1)))."\n";
            }
                echo("\n");
        }
    }    
    
    
    GenPairs(6);
    
    0:5
    1:4
    2:3
    
    0:4
    5:3
    1:2
    
    0:3
    4:2
    5:1
    
    0:2
    3:1
    4:5
    
    0:1
    2:5
    3:4