UltraMega Blog
4May/102

## Round Robin Tournament Scheduler

Here's a snippet I wrote for a project that I thought might come in handy for someone else. It generates a schedule for a round robin tournament. I found some other snippets to do this, but I found them overly complicated or lacking in other ways.

Here's an example of what this code does:

```< ?php \$players = range(1, 8);   echo 'Original List: ' . PHP_EOL; print_r(\$players); echo PHP_EOL; echo 'Round Robin Schedule: ' . PHP_EOL; print_r(generateRRSchedule(\$players)); ?>```

Output:

```Original List: Array (  => 1  => 2  => 3  => 4  => 5  => 6  => 7  => 8 )   Round Robin Schedule: Array (  => Array (  => Array (  => 1  => 8 )    => Array (  => 2  => 7 )    => Array (  => 3  => 6 )    => Array (  => 4  => 5 )   )   (...)   )```

Anyway, here's the code:

```<?php /** * Generate a round robin schedule from a list of players * * @param <array> \$players A list of players * @param <bool> \$rand Set TRUE to randomize the results * @return <array> Array of matchups separated by sets */ function generateRRSchedule(array \$players, \$rand = false) { \$numPlayers = count(\$players);   // add a placeholder if the count is odd if(\$numPlayers%2) { \$players[] = null; \$numPlayers++; }   // calculate the number of sets and matches per set \$numSets = \$numPlayers-1; \$numMatches = \$numPlayers/2;   \$matchups = array();   // generate each set for(\$j = 0; \$j < \$numSets; \$j++) { // break the list in half \$halves = array_chunk(\$players, \$numMatches); // reverse the order of one half \$halves = array_reverse(\$halves); // generate each match in the set for(\$i = 0; \$i < \$numMatches; \$i++) { // match each pair of elements \$matchups[\$j][\$i] = \$halves[\$i]; \$matchups[\$j][\$i] = \$halves[\$i]; } // remove the first player and store \$first = array_shift(\$players); // move the second player to the end of the list \$players[] = array_shift(\$players); // place the first item back in the first position array_unshift(\$players, \$first); }   // shuffle the results if desired if(\$rand) { foreach(\$matchups as &\$match) { shuffle(\$match); } shuffle(\$matchups); }   return \$matchups; } ?>```