fork download
  1. <?php
  2. class Klasemen {
  3. private $klubPoin = [];
  4.  
  5. public function __construct(array $klubList) {
  6. foreach ($klubList as $klub) {
  7. $this->klubPoin[$klub] = 0;
  8. }
  9. }
  10.  
  11. public function catatPermainan(string $klubKandang, string $klubTandang, string $skor): void {
  12. list($skorKandang, $skorTandang) = explode(':', $skor);
  13. $skorK = (int)$skorKandang;
  14. $skorT = (int)$skorTandang;
  15.  
  16. if ($skorK > $skorT) {
  17. $this->klubPoin[$klubKandang] += 3;
  18. } elseif ($skorK < $skorT) {
  19. $this->klubPoin[$klubTandang] += 3;
  20. } else {
  21. $this->klubPoin[$klubKandang]++;
  22. $this->klubPoin[$klubTandang]++;
  23. }
  24. }
  25.  
  26. public function cetakKlasemen(): array {
  27. arsort($this->klubPoin);
  28. return $this->klubPoin;
  29. }
  30.  
  31. public function ambilPeringkat(int $nomorPeringkat): string {
  32. $sorted = $this->cetakKlasemen();
  33. $keys = array_keys($sorted);
  34. return $keys[$nomorPeringkat - 1] ?? '';
  35. }
  36. }
  37.  
  38. // Contoh penggunaan:
  39. $k = new Klasemen(['Liverpool', 'Chelsea', 'Arsenal']);
  40. $k->catatPermainan('Arsenal', 'Liverpool', '2:1');
  41. $k->catatPermainan('Arsenal', 'Chelsea', '1:1');
  42. $k->catatPermainan('Chelsea', 'Arsenal', '0:3');
  43. $k->catatPermainan('Chelsea', 'Liverpool', '3:2');
  44. $k->catatPermainan('Liverpool', 'Arsenal', '2:2');
  45. $k->catatPermainan('Liverpool', 'Chelsea', '0:0');
  46.  
  47. print_r($k->cetakKlasemen());
  48. echo "Peringkat 2: " . $k->ambilPeringkat(2) . "\n";
  49.  
Success #stdin #stdout 0.03s 25748KB
stdin
Standard input is empty
stdout
Array
(
    [Arsenal] => 8
    [Chelsea] => 5
    [Liverpool] => 2
)
Peringkat 2: Chelsea