Home > Backend Development > PHP Tutorial > How Can the Shunting Yard Algorithm Simplify Mathematical Expression Evaluation in PHP?

How Can the Shunting Yard Algorithm Simplify Mathematical Expression Evaluation in PHP?

Patricia Arquette
Release: 2025-01-03 12:53:39
Original
974 people have browsed it

How Can the Shunting Yard Algorithm Simplify Mathematical Expression Evaluation in PHP?

Creating a Calculator in PHP

Simplifying mathematical expressions entered into an tag in PHP can be challenging, especially when preserving the original notation. While a brute-force approach of replacing strings with calculated values seems viable initially, it becomes inefficient.

Utilizing the Shunting Yard Algorithm

A more effective solution is the Shunting Yard Algorithm. It converts input expressions into Reverse Polish Notation (RPN). RPN simplifies calculations as operands are immediately followed by their operators.

Implementation Example

The following code provides an implementation of the Shunting Yard Algorithm in PHP:

class Expression {

    protected $tokens;
    protected $output;

    // Shunting Yard Algorithm
    public function shuntingYard($input) {
        $stack = [];
        $tokens = $this->tokenize($input);
        foreach ($tokens as $token) {
            if (is_numeric($token)) {
                $this->output[] = $token;
            } else {
                switch ($token) {
                    case '(':
                        $stack[] = $token;
                        break;
                    case ')':
                        while ($stack && end($stack) != '(') {
                            $this->output[] = array_pop($stack);
                        }
                        if (!empty($stack)) {
                            array_pop($stack);
                        }
                        break;
                    default:
                        while ($stack && $this->precedence($token) <= $this->precedence(end($stack))) {
                            $this->output[] = array_pop($stack);
                        }
                        $stack[] = $token;
                        break;
                }
            }
        }
        while (!empty($stack)) {
            $this->output[] = array_pop($stack);
        }
    }

    // Tokenize the input
    public function tokenize($input) {
        preg_match_all('~\d+|~|~U', $input, $tokens);
        return $tokens[0];
    }

    // Operator precedence
    public function precedence($operator) {
        switch ($operator) {
            case '+':
            case '-':
                return 1;
            case '*':
            case '/':
                return 2;
            default:
                return 0;
        }
    }

    // Evaluate the RPN expression
    public function evaluate() {
        $stack = [];
        foreach ($this->output as $token) {
            if (is_numeric($token)) {
                $stack[] = $token;
            } else {
                $operand2 = array_pop($stack);
                $operand1 = array_pop($stack);
                switch ($token) {
                    case '+':
                        $result = $operand1 + $operand2;
                        break;
                    case '-':
                        $result = $operand1 - $operand2;
                        break;
                    case '*':
                        $result = $operand1 * $operand2;
                        break;
                    case '/':
                        $result = $operand1 / $operand2;
                        break;
                }
                $stack[] = $result;
            }
        }
        return array_pop($stack);
    }
}

$expression = new Expression();
$expression->shuntingYard('8*(5+1)');
$result = $expression->evaluate();

echo $result; // Output: 48
Copy after login

This code translates the input into RPN, evaluates the resulting stack, and returns the final result.

The above is the detailed content of How Can the Shunting Yard Algorithm Simplify Mathematical Expression Evaluation in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template