fork download
  1. <?php
  2.  
  3. class Kamus {
  4. private $data = [];
  5.  
  6. public function tambah($kata, $sinonim) {
  7. if (!isset($this->data[$kata])) {
  8. $this->data[$kata] = [];
  9. }
  10.  
  11. $this->data[$kata] = array_merge($this->data[$kata], $sinonim);
  12.  
  13. $this->data[$kata] = array_unique($this->data[$kata]);
  14. }
  15.  
  16. public function ambilSinonim($kata) {
  17. if (!isset($this->data[$kata])) {
  18. return null;
  19. }
  20.  
  21. $hasil = [];
  22.  
  23. $hasil = array_merge($hasil, $this->data[$kata]);
  24.  
  25. foreach ($this->data as $kunci => $sinonimArray) {
  26. if ($kunci != $kata && in_array($kata, $sinonimArray)) {
  27. $hasil[] = $kunci;
  28. }
  29. }
  30.  
  31. return array_unique($hasil);
  32. }
  33. }
  34.  
  35. // Test
  36. $kamus = new Kamus();
  37. $kamus->tambah('big', ['large', 'great']);
  38. $kamus->tambah('big', ['huge', 'fat']);
  39. $kamus->tambah('huge', ['enormous', 'gigantic']);
  40.  
  41. echo "Sinonim 'big': ";
  42. print_r($kamus->ambilSinonim('big'));
  43. echo "\n";
  44.  
  45. echo "Sinonim 'huge': ";
  46. print_r($kamus->ambilSinonim('huge'));
  47. echo "\n";
  48.  
  49. echo "Sinonim 'gigantic': ";
  50. print_r($kamus->ambilSinonim('gigantic'));
  51. echo "\n";
  52.  
  53. echo "Sinonim 'colossal': ";
  54. var_dump($kamus->ambilSinonim('colossal'));
  55. echo "\n";
  56.  
  57. ?>
Success #stdin #stdout 0.04s 25880KB
stdin
Standard input is empty
stdout
Sinonim 'big': Array
(
    [0] => large
    [1] => great
    [2] => huge
    [3] => fat
)

Sinonim 'huge': Array
(
    [0] => enormous
    [1] => gigantic
    [2] => big
)

Sinonim 'gigantic': 
Sinonim 'colossal': NULL