fork download
  1. <?php
  2. class Kamus {
  3. private $kamus = [];
  4.  
  5. public function tambah(string $kata, array $sinonim) {
  6. // tidak mengembalikan hasil (void)
  7.  
  8. if(!isset($this->kamus[$kata])) {
  9. $this->kamus[$kata] = [];
  10. }
  11.  
  12. foreach($sinonim as $other_kata) {
  13. if(!in_array($other_kata, $this->kamus[$kata])) {
  14. $this->kamus[$kata][] = $other_kata;
  15. }
  16.  
  17. if (!isset($this->kamus[$other_kata])) {
  18. $this->kamus[$other_kata] = [];
  19. }
  20.  
  21. if (!in_array($kata, $this->kamus[$other_kata])) {
  22. $this->kamus[$other_kata][] = $kata;
  23. }
  24.  
  25. // foreach($sinonim as $other_kata2) {
  26. // if ($other_kata == $other_kata2) continue;
  27.  
  28. // if (!in_array($other_kata2, $this->kamus[$other_kata])) {
  29. // $this->kamus[$other_kata][] = $other_kata2;
  30. // }
  31. // }
  32. }
  33.  
  34. return;
  35. }
  36.  
  37. public function ambilSinonim(string $kata) {
  38. // mengembalikan hasil array of strings
  39. return $this->kamus[$kata];
  40. }
  41. }
  42.  
  43. $kamus = new Kamus();
  44. $kamus->tambah('big', ['large', 'great']);
  45. $kamus->tambah('big', ['huge', 'fat']);
  46. $kamus->tambah('huge', ['enormous', 'gigantic']);
  47. function cetakSinonim($kamus, $kata) {
  48. echo "Sinonim dari '$kata': ";
  49. $hasil = $kamus->ambilSinonim($kata);
  50. if ($hasil === null) {
  51. echo "null\n";
  52. } else {
  53. echo "[" . implode(", ", $hasil) . "]\n";
  54. }
  55. }
  56.  
  57. cetakSinonim($kamus, 'big');
  58. cetakSinonim($kamus, 'huge');
  59. cetakSinonim($kamus, 'gigantic');
  60. cetakSinonim($kamus, 'colossal');
  61. ?>
Success #stdin #stdout #stderr 0.03s 26164KB
stdin
Standard input is empty
stdout
Sinonim dari 'big': [large, great, huge, fat]
Sinonim dari 'huge': [big, enormous, gigantic]
Sinonim dari 'gigantic': [huge]
Sinonim dari 'colossal': null
stderr
PHP Notice:  Undefined index: colossal in /home/JZ6xLx/prog.php on line 39