fork download
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. class Klasemen
  5. {
  6. private $poin = [];
  7. private $urutanKlub = [];
  8.  
  9. public function __construct(array $klub)
  10. {
  11. foreach ($klub as $nama) {
  12. $this->poin[$nama] = 0;
  13. }
  14. $this->urutanKlub = $klub;
  15. }
  16.  
  17. public function catatPermainan(string $klubKandang, string $klubTandang, string $skor): void
  18. {
  19. [$skorKandang, $skorTandang] = array_map('intval', explode(':', $skor));
  20.  
  21. if ($skorKandang > $skorTandang) {
  22. $this->poin[$klubKandang] += 3;
  23. } elseif ($skorKandang < $skorTandang) {
  24. $this->poin[$klubTandang] += 3;
  25. } else {
  26. $this->poin[$klubKandang] += 1;
  27. $this->poin[$klubTandang] += 1;
  28. }
  29. }
  30.  
  31. public function cetakKlasemen(): array
  32. {
  33. $hasil = $this->poin;
  34. uksort($hasil, function ($a, $b) use ($hasil) {
  35. if ($hasil[$a] === $hasil[$b]) {
  36. return array_search($a, $this->urutanKlub) <=> array_search($b, $this->urutanKlub);
  37. }
  38. return $hasil[$b] <=> $hasil[$a];
  39. });
  40. return $hasil;
  41. }
  42.  
  43. public function ambilPeringkat(int $nomorPeringkat): string
  44. {
  45. $klasemen = $this->cetakKlasemen();
  46. $namaKlub = array_keys($klasemen);
  47. return $namaKlub[$nomorPeringkat - 1];
  48. }
  49. }
  50.  
  51. $klasemen = new Klasemen(['Liverpool', 'Chelsea', 'Arsenal']);
  52. $klasemen->catatPermainan('Arsenal', 'Liverpool', '2:1');
  53. $klasemen->catatPermainan('Arsenal', 'Chelsea', '1:1');
  54. $klasemen->catatPermainan('Chelsea', 'Arsenal', '0:3');
  55. $klasemen->catatPermainan('Chelsea', 'Liverpool', '3:2');
  56. $klasemen->catatPermainan('Liverpool', 'Arsenal', '2:2');
  57. $klasemen->catatPermainan('Liverpool', 'Chelsea', '0:0');
  58.  
  59. print_r($klasemen->cetakKlasemen());
  60. echo $klasemen->ambilPeringkat(2) . PHP_EOL;
Success #stdin #stdout 0.02s 25452KB
stdin
Standard input is empty
stdout
Array
(
    [Arsenal] => 8
    [Chelsea] => 5
    [Liverpool] => 2
)
Chelsea