Skip to content

Instantly share code, notes, and snippets.

@krishbhanushali
Last active July 19, 2018 19:01
Show Gist options
  • Save krishbhanushali/f225a7237719a633c535852f58dd3b86 to your computer and use it in GitHub Desktop.
Save krishbhanushali/f225a7237719a633c535852f58dd3b86 to your computer and use it in GitHub Desktop.
<?php
$polish_notation = "+ 9 * 2 6"; //space seperated polish notation
$invalid_polish_notation = "1 + 2";
$answer = polish_notation_calculator($polish_notation);
print_r($answer."\n");
$answer = polish_notation_calculator($invalid_polish_notation);
print_r($answer);
function polish_notation_calculator($polish_notation) {
$operator_stack = new Stack();
$operand_stack = new Stack();
$pending_operand = false;
$polish_notation_arr = explode(" ",$polish_notation);
for($i=0; $i < count($polish_notation_arr); $i++) {
$char = $polish_notation_arr[$i];
if ($char == "+" || $char == "-" || $char == "/" || $char == "*") {
$operator_stack->push($char);
$pending_operand = false;
}else if(is_numeric($char)){
$operand = $char;
if($pending_operand == true) {
while(!$operand_stack->is_empty()) {
$operand1 = $operand_stack->pop();
$operator = $operator_stack->pop();
if ($operator == "+") $operand = $operand1 + $operand;
else if ($operator == "-") $operand = $operand1 - $operand;
else if ($operator == "*") $operand = $operand1 * $operand;
else if ($operator == "/") $operand = $operand1 / $operand;
}
}
$operand_stack->push($operand);
$pending_operand = true;
}
}
if ($operator_stack->is_empty() || count($operand_stack)>1)
return $operand_stack->pop();
else
return "Not a valid polish notation.";
}
?>
<?php
class Stack
{
public $stack;
public function __construct() {
$this->stack = array();
}
public function push($x) {
array_unshift($this->stack,$x);
}
public function pop() {
if ($this->is_empty()) {
throw new RuntimeException("Stack is empty!!! No pop operation can be performed.");
}else {
return array_shift($this->stack);
}
}
public function top() {
return current($this->stack);
}
public function is_empty() {
return empty($this->stack);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment