Skip to content

Instantly share code, notes, and snippets.

@caseyfw
Created March 21, 2016 07:36
Show Gist options
  • Save caseyfw/00af5cfe7b48e0be8962 to your computer and use it in GitHub Desktop.
Save caseyfw/00af5cfe7b48e0be8962 to your computer and use it in GitHub Desktop.
CSL Draw Calculator
<?php
$schedule = json_decode('{
"ballmark" : {
"2016-03-14": "unisay",
"2016-03-21": "discosaur"
},
"discosaur" : {
"2016-03-14": "phoenix",
"2016-03-21": "ballmark"
},
"disky" : {
"2016-03-14": "theme",
"2016-03-21": "honey"
},
"honey" : {
"2016-03-14": "sado",
"2016-03-21": "disky"
},
"phoenix" : {
"2016-03-14": "discosaur",
"2016-03-21": "sambal"
},
"sado" : {
"2016-03-14": "honey",
"2016-03-21": "unisax"
},
"sambal" : {
"2016-03-14": "unisax",
"2016-03-21": "phoenix"
},
"theme" : {
"2016-03-14": "disky",
"2016-03-21": "unisay"
},
"unisax" : {
"2016-03-14": "sambal",
"2016-03-21": "sado"
},
"unisay" : {
"2016-03-14": "ballmark",
"2016-03-21": "theme"
}
}', true);
$nights = [
"2016-03-14",
"2016-03-21",
"2016-03-28",
"2016-04-04",
"2016-04-11",
"2016-04-18",
"2016-04-25",
"2016-05-02",
"2016-05-09",
];
$teams = [
"ballmark",
"discosaur",
"disky",
"honey",
"phoenix",
"sado",
"sambal",
"theme",
"unisax",
"unisay",
];
$currentNightIndex = 2;
if (hasNightlyDuplicates($schedule)) {
echo "A night exists where a team is scheduled to play at least twice.\n";
die;
}
if (hasRepeatGames($schedule)) {
echo "There are repeat games.\n";
die;
}
// while schedule is incomplete
while (isIncomplete($schedule, $nights)) {
// determine current night
$currentNight = $nights[$currentNightIndex];
// generate a random draw for the night
shuffle($teams);
for ($i = 0; $i < 5; $i++) {
// pair up every i and i + 5 team
$schedule[$teams[$i]][$currentNight] = $teams[$i + 5];
$schedule[$teams[$i + 5]][$currentNight] = $teams[$i];
}
// if draw is NOT legit
if (hasNightlyDuplicates($schedule) || hasRepeatGames($schedule)) {
// delete it
foreach ($schedule as &$team) {
unset($team[$currentNight]);
}
} else {
// set currentNightIndex to the next one.
$currentNightIndex++;
}
}
echo json_encode($schedule);
function hasNightlyDuplicates($schedule) {
$nights = [];
foreach ($schedule as $team => $matches) {
foreach ($matches as $night => $opponent) {
$nights[$night][] = $opponent;
}
}
foreach ($nights as $teams) {
if (count(array_unique($teams)) < count($teams)) {
return true;
}
}
return false;
}
function hasRepeatGames($schedule) {
foreach($schedule as $team => $matches) {
if (count(array_unique(array_values($matches))) < count($matches)) {
return true;
}
}
return false;
}
function isIncomplete($schedule, $nights) {
foreach($schedule as $team => $matches) {
if (count($matches) < count($nights)) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment