Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- include_once('PolishNotationValidator.php');
- use PolishNotationValidator as Validator;
- /**
- * PolishNotation class
- *
- * Polish notation calculator.
- *
- * @author Ralph Moran - ralphmoran2003@gmail.com
- * @version 1.0
- * @copyright 2018
- */
- class PolishNotation extends Validator{
- /**
- * __construct( String $sPNPattern )
- *
- * Take a pattern and calculate the results.
- *
- * @param string $pattern
- * @example new PolishNotation("/ 56 9")
- * @return int
- */
- public function __construct( String $sPNPattern ){
- $this->sPNPattern = $sPNPattern ;
- $this->aStackTokens = array_reverse( explode(" ", $this->sPNPattern) );
- try{
- if( $this->isValid() ){
- echo 'RESULT.- "' . $this->sPNPattern . '" = ' . $this->getResult() . PHP_EOL;
- }
- }catch(Exception $e){
- echo 'ERROR.- ' . $e->getMessage() . PHP_EOL;
- }
- }
- /**
- * getResult()
- *
- * Walks through $this->aTempStackResults to get the result
- *
- * @return integer | Exception
- */
- protected function getResult()
- {
- foreach( $this->aStackTokens as $sOperator ){
- if ( !is_numeric($sOperator) && $sOperator !== '' ){
- $iOp_1 = array_pop( $this->aTempStackResults );
- $iOp_2 = array_pop( $this->aTempStackResults );
- @eval('$this->iResult = ' . $iOp_1 . $sOperator . $iOp_2 . ';');
- array_push( $this->aTempStackResults, $this->iResult );
- }else{
- array_push( $this->aTempStackResults, $sOperator );
- }
- };
- // At the end left 2 or more tokens, Prefix notation format is not valid
- if ( count($this->aTempStackResults) >= 2 ){
- throw new Exception('"' . $this->sPNPattern . '" is not a valid pattern');
- }
- return $this->iResult;
- }
- }
- new PolishNotation( '/ 10 2' );
- new PolishNotation( '/ = 10 2' );
- new PolishNotation( '/ ( 10 2' );
- new PolishNotation( '/ 10 2)' );
- new PolishNotation( ' / 10 + 2' );
- new PolishNotation( ' / 10 + 2 -' );
- new PolishNotation( '/ 10' );
- new PolishNotation( '- + * 2 3 * 5 4 9' );
- new PolishNotation( '+ * + 1 2 3 4' );
Add Comment
Please, Sign In to add comment