fork download
  1. <?php
  2.  
  3. class Kamus
  4. {
  5. private $kata = [];
  6. private $sinonim = [];
  7.  
  8. public function tambah($kata, $daftarSinonim)
  9. {
  10.  
  11. if (!in_array($kata, $this->kata)) {
  12. $this->kata[] = $kata;
  13. $this->sinonim[] = [];
  14. }
  15.  
  16. $indexKata = array_search($kata, $this->kata);
  17.  
  18. foreach ($daftarSinonim as $s) {
  19.  
  20. if (!in_array($s, $this->sinonim[$indexKata])) {
  21. $this->sinonim[$indexKata][] = $s;
  22. }
  23.  
  24. if (!in_array($s, $this->kata)) {
  25. $this->kata[] = $s;
  26. $this->sinonim[] = [];
  27. }
  28.  
  29. $indexSinonim = array_search($s, $this->kata);
  30. if (!in_array($kata, $this->sinonim[$indexSinonim])) {
  31. $this->sinonim[$indexSinonim][] = $kata;
  32. }
  33. }
  34. }
  35.  
  36. public function ambilSinonim($kata)
  37. {
  38. if (!in_array($kata, $this->kata)) {
  39. return null;
  40. }
  41.  
  42. $index = array_search($kata, $this->kata);
  43. return $this->sinonim[$index];
  44. }
  45. }
  46.  
  47. $kamus = new Kamus();
  48.  
  49. $kamus->tambah('big', ['large', 'great']);
  50. $kamus->tambah('big', ['huge', 'fat']);
  51. $kamus->tambah('huge', ['enormous', 'gigantic']);
  52.  
  53. function output($result)
  54. {
  55. if ($result === null) {
  56. echo "null\n";
  57. } else {
  58. echo "['" . implode("', '", $result) . "']\n";
  59. }
  60. }
  61.  
  62. output($kamus->ambilSinonim('big'));
  63. output($kamus->ambilSinonim('huge'));
  64. output($kamus->ambilSinonim('gigantic'));
  65. output($kamus->ambilSinonim('colossal'));
  66.  
Success #stdin #stdout 0.02s 25972KB
stdin
Standard input is empty
stdout
['large', 'great', 'huge', 'fat']
['big', 'enormous', 'gigantic']
['huge']
null