Data structure & algorithm - inverse Polish four arithmetic

Posted by ScotDiddle on Tue, 01 Feb 2022 07:48:54 +0100

algorithm

1, Algorithm for converting infix expression to suffix expression:
1. Scan a infix expression from left to right.
2. If the operand is read, judge the type of the operand and store the operand in the operand stack
3. If operator is read
(1) If the operator is an open parenthesis "(", it is directly stored in the operator stack.
(2) If the operator is a closing parenthesis ")", the operator in the output operator stack is to the operand stack until the left parenthesis is is encountered.
(3) The operator is a non bracket operator:
(a) If the operator at the top of the operator stack is a bracket, it is directly stored in the operator stack.
(b) If the priority is higher or equal than the operator at the top of the operator stack, it is directly stored in the operator stack.
© If the priority is lower than the operator at the top of the operator stack, the operator at the top of the stack is output to the operand stack, and the current operator is pushed into the operator stack.
4. When there are still operators in the operator stack after the expression is read, the operators will be taken out to the operand stack in order until the operator stack is empty.

2, Evaluation algorithm of inverse Polish expression:
1. Cycle through items in grammar units.
2. If the scanned item is an operand, it is pushed into the operand stack and the next item is scanned.
3. If the scanned item is a binary operator, the operation is performed on the top two operands of the stack.
4. If the scanned item is a unary operator, the operation is performed on the top operand of the stack.
5. Push the operation result back onto the stack.
6. Repeat steps 2-5, and the result value is in the stack.

Operation results

code

using System;
using System.Collections.Generic;

namespace ReversePolish
{
    class Program
    {
        static void Main(string[] args)
        {
            string calcmode = "2.5+3*4-5*2+(15-9)/2";

            ReversePolishC polishC = new ReversePolishC();

            polishC.CalcTarget(calcmode);
        }

    }
    //Pre suffix expression
    //Reentry stack calculation
    class ReversePolishC
    {

        public float CalcTarget(string arg)
        {
            return CalcReversePolish(midToLastMode(arg));
        }
        /// <summary>
        ///Infix expression to suffix expression
        /// </summary>
        ///< param name = "Arg" > infix expression < / param >
        /// <returns></returns>
        public List<string> midToLastMode(string arg)
        {
            List<string> suffixMode = new List<string>();
            Stack<string> stack = new Stack<string>();
            string numstr = "";
            for (int i = 0; i < arg.Length; i++)
            {


                if (char.IsNumber(arg[i]) || arg[i] == '.')//number
                {
                    numstr += arg[i];

                }
                else if (arg[i].Equals('('))//brackets
                {
                    if (numstr != "")
                    {
                        suffixMode.Add(numstr);
                        numstr = "";
                    }
                    stack.Push(arg[i].ToString());
                }
                else if (arg[i].Equals(')'))//brackets
                {
                    if (numstr != "")
                    {
                        suffixMode.Add(numstr);
                        numstr = "";
                    }
                    while (stack != null)
                    {
                        string temp = stack.Pop();
                        if (temp != "(")
                        {
                            suffixMode.Add(temp);
                        }
                        else
                        {
                            break;
                        }
                    }

                }
                else if (arg[i].Equals('*') || arg[i].Equals('/'))  //Multiplication and division
                {
                    if (numstr != "")
                    {
                        suffixMode.Add(numstr);
                        numstr = "";
                    }
                    while (true)
                    {
                        string temp;
                        if (stack.Count > 0)
                        {
                            temp = stack.Peek();
                        }
                        else
                        {
                            stack.Push(arg[i].ToString());
                            break;
                        }

                        if (temp == "*" || temp == "/")
                        {
                            suffixMode.Add(stack.Pop());
                        }
                        else
                        {
                            stack.Push(arg[i].ToString());
                            break;
                        }
                    }
                }
                else if (arg[i].Equals('+') || arg[i].Equals('-')) //Addition and subtraction
                {

                    if (numstr != "")
                    {
                        suffixMode.Add(numstr);
                        numstr = "";
                    }
                    while (true)
                    {
                        string temp;
                        if (stack.Count > 0)
                        {
                            temp = stack.Peek();
                        }
                        else
                        {
                            stack.Push(arg[i].ToString());
                            break;
                        }

                        if (temp == "*" || temp == "/" || temp == "+" || temp == "-")
                        {
                            suffixMode.Add(stack.Pop());
                        }
                        else
                        {
                            stack.Push(arg[i].ToString());
                            break;
                        }
                    }
                }

            }
            if (numstr != "")
            {
                suffixMode.Add(numstr);
                numstr = "";
            }


            while (stack.Count > 0)
            {

                suffixMode.Add(stack.Pop());
            }
            //string target = "";
            for (int i = 0; i < suffixMode.Count; i++)
            {
                Console.WriteLine(suffixMode[i]);
            }
            return suffixMode;
        }

        /// <summary>
        ///The suffix expression is evaluated
        /// </summary>
        /// <param name="reversep"></param>
        float CalcReversePolish(List<string> reversep)
        {
            Stack<float> stack = new Stack<float>();
            float target;
            for (int i = 0; i < reversep.Count; i++)
            {
                if (float.TryParse(reversep[i], out target))
                {
                    stack.Push(target);
                }
                else if (reversep[i].Equals("*"))//ride
                {
                    float tempA = stack.Pop();
                    float tempB = stack.Pop();
                    target = tempB * tempA;
                    stack.Push(target);
                }
                else if (reversep[i].Equals("/")) //except
                {
                    float tempA = stack.Pop();
                    float tempB = stack.Pop();
                    target = tempB / tempA;

                    stack.Push(target);
                }
                else if (reversep[i].Equals("+")) //plus
                {
                    float tempA = stack.Pop();
                    float tempB = stack.Pop();
                    target = tempB + tempA;

                    stack.Push(target);
                }
                else if (reversep[i].Equals("-")) //reduce
                {
                    float tempA = stack.Pop();
                    float tempB = stack.Pop();
                    target = tempB - tempA;

                    stack.Push(target);
                }

            }
            Console.WriteLine("----------Calculation results------------");
            Console.WriteLine(stack.Peek());
            return stack.Peek();
        }
    }
}

reference resources

Link:
Reverse Polish notation
Dahua data structure

Topics: Algorithm data structure