Last active
August 16, 2017 18:01
-
-
Save Cleanse/bcd8405e7cf5fe17a7d692eb8e075007 to your computer and use it in GitHub Desktop.
Used an array_reverse at the end so the initial round could work with seeding a tourney.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Thanks https://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm | |
* | |
* @param int $weeks | |
* @param array $teams | |
* @return array | |
*/ | |
function generateRoundRobin($rounds = 4, $teams) | |
{ | |
//Check if team count is odd | |
if (count($teams) % 2 !== 0) { | |
$teams[] = 'BYE'; | |
} | |
$halfTeams = count($teams) / 2; | |
$mTeams = $teams; | |
array_shift($mTeams); | |
$count = count($mTeams); | |
$schedule = []; | |
for ($i = 0; $i < $rounds; $i++) { | |
$teamIndex = $i % $count; | |
$schedule[$i][] = [$teams[0], $mTeams[$teamIndex]]; | |
for ($j = 1; $j < $halfTeams; $j++) { | |
$firstTeam = ($i + $j) % $count; | |
$secondTeam = ($i + $count - $j) % $count; | |
$schedule[$i][] = [$mTeams[$firstTeam], $mTeams[$secondTeam]]; | |
} | |
} | |
return array_reverse($schedule); | |
} | |
$rounds = 7; | |
$teams = [ | |
'1', '2', '3', '4', '5', '6', '7', '8' | |
]; | |
$schedule = generateRoundRobin($rounds, $teams); | |
print_r($schedule); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment