fork download
  1. <?php
  2.  
  3. class Kamus
  4. {
  5. private $data = [];
  6.  
  7. public function tambah($word, $synonyms)
  8. {
  9. foreach($synonyms as $s)
  10. {
  11. if($s === $word)
  12. {
  13. continue;
  14. }
  15. $this->link($word, $s);
  16. $this->link($s, $word); // two-way relation
  17. }
  18. }
  19.  
  20. public function ambilSinonim($word)
  21. {
  22. if(!isset($this->data[$word]))
  23. {
  24. return null;
  25. }
  26. return array_keys($this->data[$word]);
  27. }
  28.  
  29. private function link($a, $b)
  30. {
  31. if (!isset($this->data[$a])){
  32. $this->data[$a] = [];
  33. }
  34. $this->data[$a][$b] = true;
  35. }
  36. }
  37.  
  38. function show($dictionary, $word)
  39. {
  40. $result = $dictionary->ambilSinonim($word);
  41. if($result === null)
  42. {
  43. echo "* `$word` → `NULL`\n";
  44. }
  45. else
  46. {
  47. echo "* `$word` → `[" . implode(', ', $result) . "]`\n";
  48. }
  49. }
  50.  
  51. $kamus = new Kamus();
  52. $kamus->tambah('big', ['large', 'great']);
  53. $kamus->tambah('big', ['huge', 'fat']);
  54. $kamus->tambah('huge', ['enormous', 'gigantic']);
  55.  
  56. show($kamus, 'big');
  57. show($kamus, 'huge');
  58. show($kamus, 'gigantic');
  59. show($kamus, 'colossal');
Success #stdin #stdout 0.02s 26244KB
stdin
Standard input is empty
stdout
* `big` → `[large, great, huge, fat]`
* `huge` → `[big, enormous, gigantic]`
* `gigantic` → `[huge]`
* `colossal` → `NULL`