Last active
May 28, 2023 06:37
-
-
Save stevebauman/ca9a792933cc03f1da7f0eec8b346096 to your computer and use it in GitHub Desktop.
League Table PHP Challenge
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 | |
class LeagueTable | |
{ | |
public function __construct(array $players) | |
{ | |
$this->standings = []; | |
foreach($players as $index => $p) { | |
$this->standings[$p] = [ | |
'index' => $index, | |
'games_played' => 0, | |
'score' => 0 | |
]; | |
} | |
} | |
public function recordResult(string $player, int $score) : void | |
{ | |
$this->standings[$player]['games_played']++; | |
$this->standings[$player]['score'] += $score; | |
} | |
public function playerRank(int $rank) : string | |
{ | |
$rankings = $this->standings; | |
// Uasort allows us to move elements up or down the array in | |
// comparison to their subsequent elements and maintain | |
// their string keys, which are the player names. | |
uasort($rankings, function ($a, $b) { | |
// Scores are unequal, use score to order. | |
// $b will be moved up in the array. | |
if ($a['score'] < $b['score']) { | |
return 1; | |
} | |
// $b will be moved down the array. | |
if ($a['score'] > $b['score']) { | |
return -1; | |
} | |
// Scores are equal. Use games played to order. | |
// $b will be moved up the array. | |
if ($a['games_played'] > $b['games_played']) { | |
return 1; | |
} | |
// $b will be moved down the array. | |
if ($a['games_played'] < $b['games_played']) { | |
return -1; | |
} | |
// Score and Games played are equal. Use index to order. | |
// Move $b up the array if $a has a greater index. | |
// Otherwise move $b down. | |
return $a['index'] > $b['index'] ? 1 : -1; | |
}); | |
// Since the rankings are now in order, we can get | |
// the names of the players in their ranked order | |
// -- which will be the array entry's index. | |
$ranks = array_keys($rankings); | |
// Ranks start at '1', so we'll subtract 1 before retrieving | |
// the player rank from the ordered, indexed names. | |
return $ranks[--$rank]; | |
} | |
} | |
$table = new LeagueTable(array('Mike', 'Chris', 'Arnold')); | |
$table->recordResult('Mike', 2); | |
$table->recordResult('Mike', 3); | |
$table->recordResult('Arnold', 5); | |
$table->recordResult('Chris', 5); | |
// Displays "Chris". | |
echo $table->playerRank(1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment