Advertisement
HwapX

Math Solver

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