fork download
  1. <?php
  2. Class Thesaurus {
  3. private $datas= array();
  4. public function add($word, $synonyms)
  5. {
  6. $data = [];
  7. if (array_key_exists($word,$this->datas))
  8. {
  9. //for($i=0;$i<count($synonyms);$i++){
  10. foreach ($synonyms as $synonym) {
  11. $this->datas[$word][]=$synonym;
  12. }
  13. }
  14. else
  15. {
  16. $this->datas[$word]=$synonyms;
  17. }
  18. return $this->datas;
  19. }
  20. public function getSynonyms($word){
  21. $result = array();
  22. if (array_key_exists($word, $this->datas)) {
  23. //if key = word
  24. foreach ($this->datas[$word] as $data) {
  25. $i = count($result);
  26. $result[$i] = $data;
  27. }
  28. }
  29. //key as synonym
  30. foreach ($this->datas as $key => $value) {
  31. $array_key = $this->datas[$key];
  32. if (array_search($word, $array_key) !== false) {
  33. $result[] = $key;
  34. }
  35. }
  36. if ($result == null) {
  37. return null;
  38. }
  39. return $result;
  40. }
  41. }
  42. $thesaurus = new Thesaurus;
  43. $thesaurus->add('big', ['large', 'great']);
  44. $thesaurus->add('big', ['huge', 'fat']);
  45. $thesaurus->add('huge', ['enormous', 'gigantic']);
  46.  
  47. // returns ['large', 'great', 'huge', 'fat']
  48. var_dump($thesaurus->getSynonyms('big'));
  49.  
  50. // returns ['big', 'enormous', 'gigantic']
  51. var_dump($thesaurus->getSynonyms('huge'));
  52.  
  53. // returns ['huge']
  54. var_dump($thesaurus->getSynonyms('gigantic'));
  55.  
  56. // returns null
  57. var_dump($thesaurus->getSynonyms('colossal'));
  58.  
  59.  
Success #stdin #stdout 0.02s 24372KB
stdin
Standard input is empty
stdout
array(4) {
  [0]=>
  string(5) "large"
  [1]=>
  string(5) "great"
  [2]=>
  string(4) "huge"
  [3]=>
  string(3) "fat"
}
array(3) {
  [0]=>
  string(8) "enormous"
  [1]=>
  string(8) "gigantic"
  [2]=>
  string(3) "big"
}
array(1) {
  [0]=>
  string(4) "huge"
}
NULL