Skip to content

Instantly share code, notes, and snippets.

@slav123
Last active August 29, 2015 14:11
Show Gist options
  • Save slav123/d6c66687966ac11d2585 to your computer and use it in GitHub Desktop.
Save slav123/d6c66687966ac11d2585 to your computer and use it in GitHub Desktop.
Reverse Polish Notation
<?php
// some tests to run
$tests[] = array(2, 1, '+', 3, '*');
$tests[] = array(4, 10, 5, '/', '+');
$tests[] = array(4, 13, 5, '/', '+');
$tests[] = array(4, 2, 5, '*', '+', 1, 3, 2, '*', '+', '/');
// expected resuluts
$expected = array(9, 6, 6.6, 2);
/**
* reverse Polish notation
*
* @param array $array input array
*
* @return int;
*/
function rpn($array) {
// init some variables
$numbers = array();
$return = $num1 = $num2 = 0;
// loop thru all elements
for ($a = 0, $max = count($array); $a < $max; $a++) {
// check if current element is number, and put it on stack
if (is_numeric($array[$a])) {
$numbers[] = $array[$a];
} else {
// get numbers from stack
$num1 = array_pop($numbers);
$num2 = array_pop($numbers);
// make operation
switch ($array[$a]) {
case '+':
$return = $num2 + $num1;
break;
case '-':
$return = $num2 - $num1;
break;
case '/':
$return = $num2 / $num1;
break;
case '*':
$return = $num2 * $num1;
break;
}
// push result on stack
array_push($numbers, $return);
}
}
return $return;
}
// loop thru samples
for ($a = 0, $max = count($tests); $a < $max; $a++) {
$result = rpn($tests[$a]);
if ($result !== $expected[$a]) {
echo "failed got {$result} expected {$expected[$a]}";
} else {
echo 'passed!';
}
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment