-
Reverse Polish notation
Code:
//Simple RPN (Reverse Polish notation) Engine
//This has 4 basic operators and I added a few functions.
//Play around and add other stuff it's very easy to add new fatures to it
using System;
using System.Collections.Generic;
namespace RPN
{
internal class Program
{
private static Stack<double> _stack = new Stack<double>();
//Test for operators
private static bool IsOp(string op)
{
if((op == "+") || (op == "-") ||
(op == "*") || (op == "/"))
{
return true;
}
else
{
return false;
}
}
//Test for numbers
private static bool IsNumber(string number)
{
double X;
try
{
X = double.Parse(number);
return true;
}
catch
{
return false;
}
}
private static double Expression(string expression)
{
string[] Toks = expression.Split(' ');
string sLine = string.Empty;
double First, Second = 0.0;
foreach (string Tok in Toks)
{
sLine = Tok.Trim();
if(IsNumber(sLine))
{
//Add numbers to the stack
_stack.Push(double.Parse(sLine));
}
else
{
if (IsOp(sLine)) {
//Add your operators
switch (sLine[0])
{
case '+':
First = _stack.Pop();
Second = _stack.Pop();
_stack.Push(Second + First);
break;
case '-':
First = _stack.Pop();
Second = _stack.Pop();
_stack.Push(Second - First);
break;
case '*':
First = _stack.Pop();
Second = _stack.Pop();
_stack.Push(Second * First);
break;
case '/':
First = _stack.Pop();
Second = _stack.Pop();
_stack.Push(Second / First);
break;
}
}
else
{
//Add functions below.
switch (sLine.ToUpper())
{
case "SQR":
First = _stack.Pop();
_stack.Push(First * First);
break;
case "SIN":
First = _stack.Pop();
_stack.Push(Math.Sin(First));
break;
case "COS":
First = _stack.Pop();
_stack.Push(Math.Cos(First));
break;
case "LOG":
First = _stack.Pop();
_stack.Push(Math.Log(First));
break;
case "ROUND":
First = _stack.Pop();
_stack.Push(Math.Round(First));
break;
case "MAX":
First = _stack.Pop();
Second = _stack.Pop();
_stack.Push(Math.Max(First,Second));
break;
case "MIN":
First = _stack.Pop();
Second = _stack.Pop();
_stack.Push(Math.Min(First, Second));
break;
}
}
}
}
//Return result
return _stack.Pop();
}
static void Main(string[] args)
{
int x;
//Expression to work with for more info on RPN see:
//https://en.wikipedia.org/wiki/Reverse_Polish_notation
string exp = "5.5 round 2 *";
//Above expression will output 12 since we push 5.5 on the stack
//Then we pop it off and round to 6, We then push it back and Push 2
//on to the stack and pop the two values from the stack and multiply them
//Then we return the result 12 to the top of the stack.
Console.WriteLine(Expression(exp));
Console.ReadKey();
}
}
}