Converting a regular math expression to Reverse Polish Notation (RPN), also known as postfix notation, is a two-step process:
Convert the infix expression (standard mathematical expression) to RPN using the Shunting Yard algorithm.
Evaluate the RPN expression.
Below is a sample implementation in C# that provides a basic framework for these classes (Token, Parenthesis, Number, Operation) and includes the conversion and evaluation:
csharp
using System;
using System.Collections.Generic;
public abstract class Token
{
public abstract TokenType TokenType { get; }
}
public enum TokenType
{
Number,
Operation,
Parenthesis
}
public class Number : Token
{
public double Value { get; private set; }
public Number(double value)
{
Value = value;
}
public override TokenType TokenType => TokenType.Number;
}
public class Operation : Token
{
public char Operator { get; private set; }
public int Precedence { get; private set; }
public bool IsLeftAssociative { get; private set; }
public Operation(char operatorChar, int precedence, bool isLeftAssociative)
{
Operator = operatorChar;
Precedence = precedence;
IsLeftAssociative = isLeftAssociative;
}
public override TokenType TokenType => TokenType.Operation;
}
public class Parenthesis : Token
{
public char Bracket { get; private set; }
public Parenthesis(char bracket)
{
Bracket = bracket;
}
public override TokenType TokenType => TokenType.Parenthesis;
}
public class ExpressionConverter
{
private readonly Dictionary<char, Operation> _operations = new Dictionary<char, Operation>
{
['+'] = new Operation('+', 2, true),
['-'] = new Operation('-', 2, true),
['*'] = new Operation('*', 3, true),
['/'] = new Operation('/', 3, true),
};
public List<Token> ConvertToRPN(string expression)
{
List<Token> output = new List<Token>();
Stack<Operation> operators = new Stack<Operation>();
for (int i = 0; i < expression.Length; i++)
{
char c = expression[i];
if (char.IsDigit(c))
{
double number;
int length = 0;
while (i < expression.Length && char.IsDigit(expression[i]))
{
length++;
i++;
}
i--;
number = double.Parse(expression.Substring(i - length + 1, length));
output.Add(new Number(number));
}
else if (_operations.ContainsKey(c))
{
Operation o1 = _operations[c];
while (operators.Count > 0 && _operations.ContainsKey(operators.Peek().Operator))
{
Operation o2 = operators.Peek();
if ((o1.IsLeftAssociative && o1.Precedence <= o2.Precedence) ||
(!o1.IsLeftAssociative && o1.Precedence < o2.Precedence))
{
output.Add(operators.Pop());
continue;
}
break;
}
operators.Push(o1);
}
else if (c == '(')
{
operators.Push(new Operation(c, -1, false));
}
else if (c == ')')
{
while (operators.Count > 0 && operators.Peek().Operator != '(')
{
output.Add(operators.Pop());
}
operators.Pop();
}
}
while (operators.Count > 0)
{
output.Add(operators.Pop());
}
return output;
}
}
public class RPNCalculator
{
public double Evaluate(List<Token> rpnTokens)
{
Stack<double> values = new Stack<double>();
foreach (var token in rpnTokens)
{
switch (token.TokenType)
{
case TokenType.Number:
values.Push(((Number)token).Value);
break;
case TokenType.Operation:
{
if (values.Count < 2)
throw new InvalidOperationException("Not enough values in the stack to perform an operation.");
double val2 = values.Pop();
double val1 = values.Pop();
char op = ((Operation)token).Operator;
values.Push(ApplyOperation(val1, val2, op));
break;
}
}
}
return values.Pop();
}
private double ApplyOperation(double val1, double val2, char operation)
{
return operation switch
{
'+' => val1 + val2,
'-' => val1 - val2,
'*' => val1 * val2,
'/' => val1 / val2,
_ => throw new NotSupportedException