aboutsummaryrefslogtreecommitdiff
path: root/NXP/MathExecutor.php
blob: d7eaf82e883f5bde2acb47db6bcf59d23e120c5f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
<?php
/**
 * Author: Alexander "NeonXP" Kiryukhin
 * Date: 14.03.13
 * Time: 1:01
 */
namespace NXP;

/**
 * Class MathExecutor
 * @package NXP
 */
class MathExecutor {
    const LEFT_ASSOCIATED = 'LEFT_ASSOCIATED';
    const RIGHT_ASSOCIATED = 'RIGHT_ASSOCIATED';
    const NOT_ASSOCIATED = 'NOT_ASSOCIATED';

    const UNARY  = 'UNARY';
    const BINARY = 'BINARY';

    private $operators = [ ];

    /**
     * Base math operators
     */
    public function __construct()
    {
        $this->addOperator('+', 1, function ($op1, $op2) { return $op1 + $op2; });
        $this->addOperator('-', 1, function ($op1, $op2) { return $op1 - $op2; });
        $this->addOperator('*', 2, function ($op1, $op2) { return $op1 * $op2; });
        $this->addOperator('/', 2, function ($op1, $op2) { return $op1 / $op2; });
        $this->addOperator('^', 3, function ($op1, $op2) { return pow($op1, $op2); });
    }

    /**
     * Add custom operator
     * @param string $name
     * @param int $priority
     * @param callable $callback
     * @param string $association
     * @param string $type
     */
    public function addOperator($name, $priority, callable $callback, $association = self::LEFT_ASSOCIATED, $type = self::BINARY)
    {
        $this->operators[$name] = [
            'priority'      => $priority,
            'association'   => $association,
            'type'          => $type,
            'callback'      => $callback
        ];
    }

    /**
     * Execute expression
     * @param $expression
     * @return int|float
     */
    public function execute($expression)
    {
        $reversePolishNotation = $this->convertToReversePolishNotation($expression);
        $result = $this->calculateReversePolishNotation($reversePolishNotation);

        return $result;
    }

    /**
     * Convert expression from normal expression form to RPN
     * @param $expression
     * @return array
     * @throws \Exception
     */
    protected function convertToReversePolishNotation($expression)
    {
        $stack = new \SplStack();
        $queue = [];
        $currentNumber = '';

        for ($i = 0; $i < strlen($expression); $i++)
        {
            $char = substr($expression, $i, 1);
            if  (is_numeric($char) || (($char == '.') && (strpos($currentNumber, '.')===false))) {
                $currentNumber .= $char;
            } elseif ($currentNumber!='') {
                $queue = $this->insertNumberToQueue($currentNumber, $queue);
                $currentNumber = '';
            }
            if (array_key_exists($char, $this->operators)) {
                while ($this->o1HasLowerPriority($char, $stack)) {
                    $queue[] = $stack->pop();
                }
                $stack->push($char);
            }
            if ($char == '(') {
                $stack->push($char);
            }
            if ($char == ')') {
                if ($currentNumber!='') {
                    $queue = $this->insertNumberToQueue($currentNumber, $queue);
                    $currentNumber = '';
                }
                while (($stackChar = $stack->pop()) != '(') {
                    $queue[] = $stackChar;
                }
                /**
                 * @TODO parse functions here
                 */
            }
        }

        if ($currentNumber!='') {
            $queue = $this->insertNumberToQueue($currentNumber, $queue);
        }

        while (!$stack->isEmpty()) {
            $queue[] = ($char = $stack->pop());
            if (!array_key_exists($char, $this->operators)) {
                throw new \Exception('Opening bracket has no closing bracket');
            }
        }

        return $queue;
    }

    /**
     * Calculate value of expression
     * @param array $expression
     * @return int|float
     * @throws \Exception
     */
    protected function calculateReversePolishNotation(array $expression)
    {
        $stack = new \SplStack();
        foreach ($expression as $element) {
            if (is_numeric($element)) {
                $stack->push($element);
            } elseif (array_key_exists($element, $this->operators))  {
                $operator = $this->operators[$element];
                switch ($operator['type']) {
                    case self::BINARY:
                        $op2 = $stack->pop();
                        $op1 = $stack->pop();
                        $operatorResult = $operator['callback']($op1, $op2);
                        break;
                    case self::UNARY:
                        $op = $stack->pop();
                        $operatorResult = $operator['callback']($op);
                        break;
                    default:
                        throw new \Exception('Incorrect type');
                }
                $stack->push($operatorResult);
            }
        }
        $result = $stack->pop();
        if (!$stack->isEmpty()) {
            throw new \Exception('Incorrect expression');
        }

        return $result;
    }

    /**
     * @param $char
     * @param $stack
     * @return bool
     */
    private function o1HasLowerPriority($char, \SplStack $stack) {
        if (($stack->isEmpty()) || ($stack->top() == '(')) {
            return false;
        }
        $stackTopAssociation = $this->operators[$stack->top()]['association'];
        $stackTopPriority = $this->operators[$stack->top()]['priority'];
        $charPriority = $this->operators[$char]['priority'];


        return
            (($stackTopAssociation != self::LEFT_ASSOCIATED) && ($stackTopPriority > $charPriority)) ||
            (($stackTopAssociation == self::LEFT_ASSOCIATED) && ($stackTopPriority >= $charPriority));
    }

    /**
     * @param string $currentNumber
     * @param array $queue
     * @return array
     */
    private function insertNumberToQueue($currentNumber, $queue)
    {
        if ($currentNumber[0]=='.') {
            $currentNumber = '0'.$currentNumber;
        }
        $currentNumber = trim($currentNumber, '.');
        $queue[] = $currentNumber;

        return $queue;
    }

}