fork download
  1. <?php
  2.  
  3. class Node {
  4. public $question;
  5. public $trueBranch;
  6. public $falseBranch;
  7.  
  8. public function __construct($question, $trueBranch, $falseBranch) {
  9. $this->question = $question;
  10. $this->trueBranch = $trueBranch;
  11. $this->falseBranch = $falseBranch;
  12. }
  13. }
  14.  
  15. class DiagnosisSystem {
  16. private $tree;
  17.  
  18. public function __construct($tree) {
  19. $this->tree = $tree;
  20. }
  21.  
  22. public function diagnose() {
  23. return $this->traverse($this->tree);
  24. }
  25.  
  26. private function traverse($node) {
  27. if ($node instanceof Node) {
  28. $answer = $this->askQuestion($node->question);
  29. if ($answer) {
  30. return $this->traverse($node->trueBranch);
  31. } else {
  32. return $this->traverse($node->falseBranch);
  33. }
  34. } else {
  35. return $node; // Leaf node (diagnosis)
  36. }
  37. }
  38.  
  39. private function askQuestion($question) {
  40. echo $question . " (yes/no): ";
  41. $handle = fopen ("php://stdin","r");
  42. $line = fgets($handle);
  43. return trim($line) === 'yes';
  44. }
  45. }
  46.  
  47. $tree = new Node('Do you have a fever?',
  48. new Node('Do you have a cough?', 'You may have a flu.', 'You may have a fever.'),
  49. new Node('Do you have a cough?', 'You may have a cold.', 'No diagnosis available.')
  50. );
  51.  
  52. $system = new DiagnosisSystem($tree);
  53. echo $system->diagnose();
  54.  
Success #stdin #stdout 0.02s 26104KB
stdin
Standard input is empty
stdout
Do you have a fever? (yes/no): Do you have a cough? (yes/no): No diagnosis available.