Guest User

Untitled

a guest
May 21st, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. <?php
  2.  
  3. include_once('PolishNotationValidator.php');
  4.  
  5. use PolishNotationValidator as Validator;
  6.  
  7. /**
  8. * PolishNotation class
  9. *
  10. * Polish notation calculator.
  11. *
  12. * @author Ralph Moran - ralphmoran2003@gmail.com
  13. * @version 1.0
  14. * @copyright 2018
  15. */
  16. class PolishNotation extends Validator{
  17.  
  18. /**
  19. * __construct( String $sPNPattern )
  20. *
  21. * Take a pattern and calculate the results.
  22. *
  23. * @param string $pattern
  24. * @example new PolishNotation("/ 56 9")
  25. * @return int
  26. */
  27. public function __construct( String $sPNPattern ){
  28.  
  29. $this->sPNPattern = $sPNPattern ;
  30. $this->aStackTokens = array_reverse( explode(" ", $this->sPNPattern) );
  31.  
  32. try{
  33. if( $this->isValid() ){
  34. echo 'RESULT.- "' . $this->sPNPattern . '" = ' . $this->getResult() . PHP_EOL;
  35. }
  36.  
  37. }catch(Exception $e){
  38. echo 'ERROR.- ' . $e->getMessage() . PHP_EOL;
  39. }
  40.  
  41. }
  42.  
  43. /**
  44. * getResult()
  45. *
  46. * Walks through $this->aTempStackResults to get the result
  47. *
  48. * @return integer | Exception
  49. */
  50. protected function getResult()
  51. {
  52. foreach( $this->aStackTokens as $sOperator ){
  53.  
  54. if ( !is_numeric($sOperator) && $sOperator !== '' ){
  55. $iOp_1 = array_pop( $this->aTempStackResults );
  56. $iOp_2 = array_pop( $this->aTempStackResults );
  57.  
  58. @eval('$this->iResult = ' . $iOp_1 . $sOperator . $iOp_2 . ';');
  59.  
  60. array_push( $this->aTempStackResults, $this->iResult );
  61. }else{
  62. array_push( $this->aTempStackResults, $sOperator );
  63. }
  64. };
  65.  
  66. // At the end left 2 or more tokens, Prefix notation format is not valid
  67. if ( count($this->aTempStackResults) >= 2 ){
  68. throw new Exception('"' . $this->sPNPattern . '" is not a valid pattern');
  69. }
  70.  
  71. return $this->iResult;
  72. }
  73.  
  74. }
  75.  
  76. new PolishNotation( '/ 10 2' );
  77. new PolishNotation( '/ = 10 2' );
  78. new PolishNotation( '/ ( 10 2' );
  79. new PolishNotation( '/ 10 2)' );
  80. new PolishNotation( ' / 10 + 2' );
  81. new PolishNotation( ' / 10 + 2 -' );
  82. new PolishNotation( '/ 10' );
  83. new PolishNotation( '- + * 2 3 * 5 4 9' );
  84. new PolishNotation( '+ * + 1 2 3 4' );
Add Comment
Please, Sign In to add comment