fork download
  1. <?php
  2.  
  3. class Kamus
  4. {
  5. private $data = [];
  6.  
  7. public function tambah($kata, $sinonim)
  8. {
  9. if (! isset($this->data[$kata])) {
  10. $this->data[$kata] = [];
  11. }
  12.  
  13. foreach ($sinonim as $s) {
  14. if (! in_array($s, $this->data[$kata])) {
  15. $this->data[$kata][] = $s;
  16. }
  17.  
  18. if (! isset($this->data[$s])) {
  19. $this->data[$s] = [];
  20. }
  21.  
  22. if (! in_array($kata, $this->data[$s])) {
  23. $this->data[$s][] = $kata;
  24. }
  25. }
  26. }
  27.  
  28. public function ambilSinonim($kata)
  29. {
  30. if (! isset($this->data[$kata])) {
  31. return null;
  32. }
  33.  
  34. $hasil = [];
  35. $dikunjungi = [];
  36. $antrian = [$kata];
  37.  
  38. while (! empty($antrian)) {
  39. $current = array_shift($antrian);
  40. if (isset($dikunjungi[$current])) {
  41. continue;
  42. }
  43.  
  44. $dikunjungi[$current] = true;
  45.  
  46. if (isset($this->data[$current])) {
  47. foreach ($this->data[$current] as $s) {
  48. if (! isset($dikunjungi[$s])) {
  49. $hasil[$s] = true;
  50. $antrian[] = $s;
  51. }
  52. }
  53. }
  54. }
  55.  
  56. return array_values(array_keys($hasil));
  57. }
  58. }
  59.  
  60. $kamus = new Kamus;
  61. $kamus->tambah('big', ['large', 'great']);
  62. $kamus->tambah('big', ['huge', 'fat']);
  63. $kamus->tambah('huge', ['enormous', 'gigantic']);
  64.  
  65. echo "Sinonim dari 'big':\n";
  66. print_r($kamus->ambilSinonim('big'));
  67.  
  68. echo "Sinonim dari 'huge':\n";
  69. print_r($kamus->ambilSinonim('huge'));
  70.  
  71. echo "Sinonim dari 'gigantic':\n";
  72. print_r($kamus->ambilSinonim('gigantic'));
  73.  
  74. echo "Sinonim dari 'colossal':\n";
  75. print_r($kamus->ambilSinonim('colossal'));
  76. if ($hasil === null) {
  77. echo "null\n";
  78. } else {
  79. print_r($hasil);
  80. }
  81.  
Success #stdin #stdout #stderr 0.02s 26220KB
stdin
Standard input is empty
stdout
Sinonim dari 'big':
Array
(
    [0] => large
    [1] => great
    [2] => huge
    [3] => fat
    [4] => enormous
    [5] => gigantic
)
Sinonim dari 'huge':
Array
(
    [0] => big
    [1] => enormous
    [2] => gigantic
    [3] => large
    [4] => great
    [5] => fat
)
Sinonim dari 'gigantic':
Array
(
    [0] => huge
    [1] => big
    [2] => enormous
    [3] => large
    [4] => great
    [5] => fat
)
Sinonim dari 'colossal':
null
stderr
PHP Notice:  Undefined variable: hasil in /home/3JQoQi/prog.php on line 76