fork download
  1. <?php
  2.  
  3. class Klasemen
  4. {
  5. private $poinKlub = [];
  6.  
  7. public function __construct($daftarKlub)
  8. {
  9. foreach ($daftarKlub as $klub) {
  10. $this->poinKlub[$klub] = 0;
  11. }
  12. }
  13.  
  14. public function catatPermainan($klubKandang, $klubTandang, $skor)
  15. {
  16.  
  17. list($skorKandang, $skorTandang) = explode(':', $skor);
  18. $skorKandang = (int)$skorKandang;
  19. $skorTandang = (int)$skorTandang;
  20.  
  21. if ($skorKandang > $skorTandang) {
  22. $this->poinKlub[$klubKandang] += 3;
  23. } elseif ($skorKandang < $skorTandang) {
  24. $this->poinKlub[$klubTandang] += 3;
  25. } else {
  26. // Seri
  27. $this->poinKlub[$klubKandang] += 1;
  28. $this->poinKlub[$klubTandang] += 1;
  29. }
  30. }
  31.  
  32. public function cetakKlasemen()
  33. {
  34. arsort($this->poinKlub);
  35. return $this->poinKlub;
  36. }
  37.  
  38. public function ambilPeringkat($peringkat)
  39. {
  40. $klasemen = $this->cetakKlasemen();
  41. $klubList = array_keys($klasemen);
  42.  
  43. if ($peringkat < 1 || $peringkat > count($klubList)) {
  44. return null; // Kalau out of range
  45. }
  46.  
  47. return $klubList[$peringkat - 1];
  48. }
  49. }
  50.  
  51. $klasemen = new Klasemen(['Liverpool', 'Chelsea', 'Arsenal']);
  52.  
  53. $klasemen->catatPermainan('Arsenal', 'Liverpool', '2:1');
  54. $klasemen->catatPermainan('Arsenal', 'Chelsea', '1:1');
  55. $klasemen->catatPermainan('Chelsea', 'Arsenal', '0:3');
  56. $klasemen->catatPermainan('Chelsea', 'Liverpool', '3:2');
  57. $klasemen->catatPermainan('Liverpool', 'Arsenal', '2:2');
  58. $klasemen->catatPermainan('Liverpool', 'Chelsea', '0:0');
  59.  
  60. print_r($klasemen->cetakKlasemen());
  61.  
  62. echo 'Peringkat ke-2: ' . $klasemen->ambilPeringkat(2);
  63.  
Success #stdin #stdout 0.04s 25476KB
stdin
Standard input is empty
stdout
Array
(
    [Arsenal] => 8
    [Chelsea] => 5
    [Liverpool] => 2
)
Peringkat ke-2: Chelsea