Something went wrong. Try again.
My attempts at exercism.org
Something went wrong. Try again.
2.9 kB · 122 lines
PHP
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123<?php
declare(strict_types=1);
class Tournament{ private const HEADER = "Team | MP | W | D | L | P";
public function tally(string $input): string { if ($input === "") { return self::HEADER; }
$teams = [];
foreach ($this->parseInput($input) as [$team1, $team2, $result]) { $this->initTeam($teams, $team1); $this->initTeam($teams, $team2);
$this->updateMatchesPlayed($teams, $team1, $team2); $this->updateMatchResult($teams, $team1, $team2, $result); }
$this->sortTeams($teams);
return $this->generateTable($teams); }
private function parseInput(string $input): array { $rows = explode("\n", $input); $matches = [];
foreach ($rows as $row) { if ($row === "") { continue; }
$matches[] = explode(";", $row); }
return $matches; }
private function initTeam(array &$teams, string $team): void { if (!isset($teams[$team])) { $teams[$team] = [ "MP" => 0, "W" => 0, "D" => 0, "L" => 0, "P" => 0, ]; } }
private function updateMatchesPlayed( array &$teams, string $team1, string $team2, ): void { $teams[$team1]["MP"]++; $teams[$team2]["MP"]++; }
private function updateMatchResult( array &$teams, string $team1, string $team2, string $result, ): void { switch ($result) { case "win": $teams[$team1]["W"]++; $teams[$team2]["L"]++; $teams[$team1]["P"] += 3; break;
case "loss": $teams[$team2]["W"]++; $teams[$team1]["L"]++; $teams[$team2]["P"] += 3; break;
case "draw": $teams[$team1]["D"]++; $teams[$team2]["D"]++; $teams[$team1]["P"]++; $teams[$team2]["P"]++; break; } }
private function sortTeams(array &$teams): void { uksort($teams, function ($teamA, $teamB) use ($teams) { return $teams[$teamB]["P"] <=> $teams[$teamA]["P"] ?: strcmp($teamA, $teamB); }); }
private function generateTable(array $teams): string { $output = self::HEADER;
foreach ($teams as $team => $stats) { $output .= sprintf( "\n%-31s| %2d | %2d | %2d | %2d | %2d", $team, $stats["MP"], $stats["W"], $stats["D"], $stats["L"], $stats["P"], ); }
return $output; }}