4May/100
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
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
Round Robin Schedule:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 8
)
[1] => Array
(
[0] => 2
[1] => 7
)
[2] => Array
(
[0] => 3
[1] => 6
)
[3] => Array
(
[0] => 4
[1] => 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[1] = array_reverse($halves[1]); // generate each match in the set for($i = 0; $i < $numMatches; $i++) { // match each pair of elements $matchups[$j][$i][0] = $halves[0][$i]; $matchups[$j][$i][1] = $halves[1][$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; } ?>
Similar Posts:
- PHP: Process Array Items With array_map
- Snippet: Fetch Twitter Feed (With Retweets) in PHP
- Bypassing Register_Globals in PHP
