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