/
RPN.php
34 lines (31 loc) · 819 Bytes
/
RPN.php
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
<?php
/**
* Created by PhpStorm.
* User: theki
* Date: 19.09.14
* Time: 15:21
*/
require_once 'OperationFactory.php';
/**
* Class RPN (Riverse Polish Notation
* perform arythmetic operation
* use Factory Method to create operation classes
*/
class RPN {
public function calculate($expression)
{
$stack = array();
foreach ($expression as $part) {
if (in_array($part, array('+', '-', '*', '/'))) {
$b = array_pop($stack);
$a = array_pop($stack);
$operation = OperationFactory::createOperation($part);
$result = $operation->calculate($a, $b);
array_push($stack, $result);
} else {
array_push($stack, $part);
}
}
return $stack[0];
}
}