Advertisement
HwapX

Math Solver - Shunting Yard

Oct 29th, 2015
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.48 KB | None | 0 0
  1. <?php
  2.  
  3. function tokenize($expr) {
  4.     preg_match_all('/(?:-|)\d+|\+|-|\*|\/|\(|\)/', $expr, $match);
  5.     $match  = $match[0];
  6.     $tokens = array();
  7.     $stack  = array();
  8.     $precedence = array('+' => 1, '-' => 1, '*' => 2, '/' => 2);
  9.    
  10.     while($match) {
  11.         $token = array_shift($match);
  12.        
  13.         if(is_numeric($token)) {
  14.             array_push($tokens, $token);
  15.         }
  16.         else {
  17.             if($token === ')') {
  18.                 while($stack && end($stack) !== '(') {
  19.                     array_push($tokens, array_pop($stack));
  20.                 }
  21.                
  22.                 array_pop($stack);
  23.                 continue;
  24.             }
  25.            
  26.             while($token !== '(' && ($stack && end($stack) !== '(') && $precedence[$token] < $precedence[end($stack)]) {
  27.                 array_push($tokens, array_pop($stack));
  28.             }
  29.            
  30.             array_push($stack, $token);
  31.         }
  32.     }
  33.    
  34.     return array_merge($tokens, array_reverse($stack));
  35. }
  36.  
  37. function resolve($math) {  
  38.     $funcs = array(
  39.         '+' => function ($left, $right) { return $left + $right; },
  40.         '-' => function ($left, $right) { return $left - $right; },
  41.         '/' => function ($left, $right) { return $left / $right; },
  42.         '*' => function ($left, $right) { return $left * $right; }
  43.     );
  44.    
  45.     $stack = array();
  46.    
  47.     while(count($math) > 1) {
  48.         $token = array_shift($math);
  49.        
  50.         if(!is_numeric($token)) {
  51.             $token = $funcs[$token](array_shift($math), array_shift($math));
  52.         }
  53.        
  54.         array_push($stack, $token);
  55.     }
  56.    
  57.     return $stack[0];
  58. }
  59.  
  60. header('content-type: text/plain');
  61. $math = tokenize('2*3+4*(5 - 6)');
  62. echo implode(' ', $math) . PHP_EOL;
  63. echo resolve($math);
  64.  
  65. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement