Showing posts with label stac. Show all posts
Showing posts with label stac. Show all posts

Wednesday, September 9, 2015

Reverse Polish notation Calculator using stack (for better understanding oop concept)

<?php

class Stack {
    public $array = array();
    public $index = -1;

    public function isEmpty()
    {
        if($this->index == -1){
            return true;
        }else{
            return false;
        }
    }
    public function push($element)
    {
        $this->index++;
        $this->array[$this->index] = $element;
    }

    public function pop()
    {
        //return $this->array[$this->index--];
        if($this->isEmpty()){
           echo 'Nothing to pop';
        }else{
            $element = $this->array[$this->index];
            unset($this->array[$this->index]);
            $this->index--;
            return $element;

        }

    }
    public function calculator($value1, $value2, $operator){
        if($operator == "+"){
            $result = $value1 + $value2;
        } elseif($operator == "-"){
            $result = $value1 - $value2;
        } elseif($operator == "*"){
            $result = $value1 * $value2;
        } elseif($operator == "/"){
            $result = $value1 / $value2;
        }

        return $result;
    }

}
$stack = new Stack();
if(isset($_POST['numbers'])){
    $numbers = trim($_POST['numbers']);
    $numbers = explode(' ', $numbers);
    foreach ($numbers as $number) {
       if(is_numeric($number)) {
           $number = intval($number);
           $stack->push($number);
       }else{
           $value2 = $stack->pop();
           $value1 = $stack->pop();
           $result = $stack->calculator($value1, $value2, $number);
           $stack->push($result);
       }
    }
$result = $stack->pop();
    echo $result;
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<form method="post" action="">
    <input type="text" name="numbers" id="">
    <input type="submit" name="submit" id="">
</form>
</body>
</html>

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }