Skip to content

Instantly share code, notes, and snippets.

@HarishChaudhari
Created June 24, 2015 14:14
Show Gist options
  • Save HarishChaudhari/92a4c940dd5abd037b70 to your computer and use it in GitHub Desktop.
Save HarishChaudhari/92a4c940dd5abd037b70 to your computer and use it in GitHub Desktop.
<?php
class polishcalculator {
/**
* Variables
*/
private $expected;
private $polishexprestion;
private $token;
private $result;
private $isValid;
private $stack;
public function __construct($postfixpolish) {
$this->polishexprestion = $postfixpolish;
}
/**
* Evaluation function
*/
public function evaluate() {
$this->result = 0;
$this->isValid = false;
//validate
$this->isValid = $this->isExpressionValid();
if( $this->isValid ) {
//split expression
$this->token = $this->splitexpression();
//store in stack
$this->result = $this->storeInStackAndCalc();
}
return (int)$this->result;
}
/**
* Expression validation
*/
public function isExpressionValid() {
// is empty
$isValidArr[] = ( isset($this->polishexprestion) && empty($this->polishexprestion) ) ? false : true;
// check string via regex, allow numbers and operators only
preg_match("/^[0-9 \+\*\/\-\^\%]+$/", $this->polishexprestion, $output_array);
$isValidArr[] = ( isset($output_array) && !is_array($output_array) && count($output_array) == 0 ) ? false : true;
return ( in_array( false, $isValidArr ) ) ? false : true;
}
/**
* Split expression by space
*/
public function splitexpression() {
return preg_split('/[\s]+/', trim($this->polishexprestion));
}
/**
* Store the tokens in stack and calculate the expressions
*/
public function storeInStackAndCalc() {
$this->stack = Array();
foreach ( $this->token as $token ) {
if( preg_match("/^[\+\*\/\-\^\%]+$/", $token ) === 0 ) {
// IF NO OPERATORS THEN PUSH TO STACK
array_push($this->stack, $token);
} else {
// IF OPERATOR THEN POP AND CALCULATE
$firstNumber = $secondNumber = 0;
$operator = $token;
if( $operator !== '%' ) {
// DO NOT POP EXTRA ELEMENT IN CASE OF % AS IN OUR CASE IT IS UNARY OPERATOR
$secondNumber = array_pop($this->stack);
}
$firstNumber = array_pop($this->stack);
if( $operator == '^' ) {
// POWER
$pushtostack = pow($firstNumber,$secondNumber);
} else if( $operator == '%' ) {
// PERCENTAGE
$pushtostack = $firstNumber / 100;
} else {
// ADD, SUB, MUL, DIV
$expression = $firstNumber . $operator . $secondNumber;
$pushtostack = eval('return '.$expression.';');
}
// Push the calculated result to stack
array_push($this->stack, $pushtostack );
}
}
return array_pop($this->stack);
}
}
// EOF :)
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment