fork download
  1.  
  2. <?php
  3. class Klasemen {
  4. private $clubs;
  5. private $points;
  6.  
  7. // Constructor to initialize clubs
  8. public function __construct($clubList) {
  9. $this->clubs = $clubList;
  10. $this->points = array_fill(0, count($clubList), 0);
  11. }
  12.  
  13. // Method to record match results
  14. public function catatPertandingan($homeClub, $awayClub, $score) {
  15. // Find indices of the clubs
  16. $homeIndex = array_search($homeClub, $this->clubs);
  17. $awayIndex = array_search($awayClub, $this->clubs);
  18.  
  19. // Validate clubs exist
  20. if ($homeIndex === false || $awayIndex === false) {
  21. throw new Exception("Club not found in the league");
  22. }
  23.  
  24. // Parse scores
  25. list($homeScore, $awayScore) = explode(':', $score);
  26.  
  27. // Determine points allocation
  28. if ($homeScore > $awayScore) {
  29. // Home team wins
  30. $this->points[$homeIndex] += 3;
  31. } elseif ($homeScore < $awayScore) {
  32. // Away team wins
  33. $this->points[$awayIndex] += 3;
  34. } else {
  35. // Draw
  36. $this->points[$homeIndex] += 1;
  37. $this->points[$awayIndex] += 1;
  38. }
  39. }
  40.  
  41. // Method to print current league standings
  42. public function cetakKlasemen() {
  43. // Create an array of club-point pairs for sorting
  44. $standings = array_map(null, $this->clubs, $this->points);
  45.  
  46. // Sort standings by points in descending order
  47. usort($standings, function($a, $b) {
  48. return $b[1] - $a[1];
  49. });
  50.  
  51. // Print or return standings
  52. $result = [];
  53. foreach ($standings as $standing) {
  54. $result[$standing[0]] = $standing[1];
  55. }
  56. return $result;
  57. }
  58.  
  59. // Method to get club ranking by position
  60. public function ambilPeringkat($position) {
  61. $standings = $this->cetakKlasemen();
  62. $ranks = array_keys($standings);
  63.  
  64. // Check if position is valid
  65. if ($position < 1 || $position > count($ranks)) {
  66. throw new Exception("Invalid ranking position");
  67. }
  68.  
  69. return $ranks[$position - 1];
  70. }
  71. }
  72.  
  73. // Example usage
  74. $klasemen = new Klasemen(['Liverpool', 'Chelsea', 'Arsenal']);
  75. $klasemen->catatPertandingan('Arsenal', 'Liverpool', '2:1');
  76. $klasemen->catatPertandingan('Arsenal', 'Chelsea', '1:1');
  77. $klasemen->catatPertandingan('Chelsea', 'Arsenal', '0:3');
  78. $klasemen->catatPertandingan('Chelsea', 'Liverpool', '3:2');
  79. $klasemen->catatPertandingan('Liverpool', 'Arsenal', '2:2');
  80. $klasemen->catatPertandingan('Liverpool', 'Chelsea', '0:0');
  81.  
  82. // Print standings
  83. print_r($klasemen->cetakKlasemen());
  84.  
  85. // Get club at specific ranking
  86. echo $klasemen->ambilPeringkat(2);
  87. ?>
  88.  
Success #stdin #stdout 0.03s 25900KB
stdin
Standard input is empty
stdout
Array
(
    [Arsenal] => 8
    [Chelsea] => 5
    [Liverpool] => 2
)
Chelsea