Advertisement
zlatkov

CalculateExpression

Jan 15th, 2013
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace CalculateExpression
  8. {
  9.     class CalculateExpression
  10.     {
  11.         static int GetPriority(char arithmeticOperator)
  12.         {
  13.             if (arithmeticOperator == '+' || arithmeticOperator == '-')
  14.             {
  15.                 return 0;
  16.             }
  17.             else
  18.             {
  19.                 return 1;
  20.             }
  21.         }
  22.  
  23.         static bool IsOperator(char ch)
  24.         {
  25.             return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
  26.         }
  27.  
  28.         static KeyValuePair<int, double> GetNumber(int startIndex, string expression)
  29.         {
  30.             string number = "";
  31.             int endIndex = startIndex + 1;
  32.  
  33.             while (endIndex < expression.Length && ((expression[endIndex] >= '0' && expression[endIndex] <= '9') || expression[endIndex] == '.'))
  34.             {
  35.                 endIndex++;  
  36.             }
  37.  
  38.             endIndex--;
  39.             KeyValuePair<int, double> result = new KeyValuePair<int, double>(endIndex, double.Parse(expression.Substring(startIndex, endIndex - startIndex + 1)));
  40.  
  41.             return result;
  42.         }
  43.  
  44.         static KeyValuePair<int, List<string>> GetFunctionParameters(int startIndex, string expression)
  45.         {
  46.             List<string> parameters = new List<string>();
  47.             string currentParameter = "";
  48.  
  49.             int balancedBrackets = 1;
  50.             int endIndex = startIndex + 1;
  51.             while (balancedBrackets != 0 && endIndex < expression.Length)
  52.             {
  53.                 if (expression[endIndex] == ',' && balancedBrackets == 1)
  54.                 {
  55.                     parameters.Add(currentParameter);
  56.                     currentParameter = "";
  57.                 }
  58.                 else
  59.                 {
  60.                     if (expression[endIndex] == '(')
  61.                     {
  62.                         balancedBrackets++;
  63.                     }
  64.                     else if (expression[endIndex] == ')')
  65.                     {
  66.                         balancedBrackets--;
  67.                     }
  68.  
  69.                     if (balancedBrackets != 0)
  70.                     {
  71.                         currentParameter += expression[endIndex];
  72.                     }
  73.                 }
  74.                 endIndex++;
  75.             }
  76.             endIndex--;
  77.  
  78.             if (currentParameter != String.Empty)
  79.             {
  80.                 parameters.Add(currentParameter);
  81.             }
  82.  
  83.             KeyValuePair<int, List<string>> result = new KeyValuePair<int, List<string>>(endIndex, parameters);
  84.             return result;
  85.         }
  86.  
  87.         static KeyValuePair<int, double> CalculateLogarithm(int startIndex, string expression)
  88.         {
  89.             KeyValuePair<int, List<string>> functionParameter = GetFunctionParameters(startIndex + 2, expression);
  90.  
  91.             double parameterValue = Calculate(functionParameter.Value[0]);
  92.             KeyValuePair<int, double> result = new KeyValuePair<int,double>(functionParameter.Key, Math.Log(parameterValue));
  93.             return result;
  94.         }
  95.  
  96.         static KeyValuePair<int, double> CalculateSqrt(int startIndex, string expression)
  97.         {
  98.             KeyValuePair<int, List<string>> functionParameter = GetFunctionParameters(startIndex + 4, expression);
  99.  
  100.             double parameterValue = Calculate(functionParameter.Value[0]);
  101.             KeyValuePair<int, double> result = new KeyValuePair<int, double>(functionParameter.Key, Math.Sqrt(parameterValue));
  102.             return result;
  103.         }
  104.  
  105.         static KeyValuePair<int, double> CalculatePow(int startIndex, string expression)
  106.         {
  107.             KeyValuePair<int, List<string>> functionParameters = GetFunctionParameters(startIndex + 3, expression);
  108.  
  109.             double parameter1Value = Calculate(functionParameters.Value[0]);
  110.             double parameter2Value = Calculate(functionParameters.Value[1]);
  111.             KeyValuePair<int, double> result = new KeyValuePair<int, double>(functionParameters.Key, Math.Pow(parameter1Value, parameter2Value));
  112.             return result;
  113.         }
  114.  
  115.         static List<KeyValuePair<int, double>> ReversePolishNotation(string expression)
  116.         {
  117.             expression = "(" + expression + ")";
  118.             List<KeyValuePair<int, double>> values = new List<KeyValuePair<int, double>>();
  119.             Stack<char> stack = new Stack<char>();
  120.  
  121.             int index = 0;
  122.             while (index < expression.Length)
  123.             {
  124.                 if (expression[index] == '(')
  125.                 {
  126.                     stack.Push('(');
  127.                 }
  128.                 else if (expression[index] == ')')
  129.                 {
  130.                     while (stack.Count > 0 && stack.Peek() != '(')
  131.                     {
  132.                         values.Add(new KeyValuePair<int, double>(1, (double)stack.Peek()));
  133.                         stack.Pop();
  134.                     }
  135.                     stack.Pop();
  136.                 }
  137.                 else if (IsOperator(expression[index]))
  138.                 {
  139.                     while (stack.Count > 0 && IsOperator(stack.Peek()) && GetPriority(expression[index]) <= GetPriority(stack.Peek()))
  140.                     {
  141.                         values.Add(new KeyValuePair<int, double>(1, (double)stack.Pop()));
  142.                     }
  143.                     stack.Push(expression[index]);
  144.                 }
  145.                 else if (expression[index] >= '0' && expression[index] <= '9')
  146.                 {
  147.                     KeyValuePair<int, double> number = GetNumber(index, expression);
  148.                     values.Add(new KeyValuePair<int, double>(0, number.Value));
  149.                     index = number.Key;
  150.                 }
  151.                 else if (expression[index] == 'l')
  152.                 {
  153.                     KeyValuePair<int, double> logarithmResult = CalculateLogarithm(index, expression);
  154.                     values.Add(new KeyValuePair<int, double>(0, logarithmResult.Value));
  155.                     index = logarithmResult.Key;
  156.                 }
  157.                 else if (expression[index] == 's')
  158.                 {
  159.                     KeyValuePair<int, double> sqrtResult = CalculateSqrt(index, expression);
  160.                     values.Add(new KeyValuePair<int, double>(0, sqrtResult.Value));
  161.                     index = sqrtResult.Key;
  162.                 }
  163.                 else if (expression[index] == 'p')
  164.                 {
  165.                     KeyValuePair<int, double> powResult = CalculatePow(index, expression);
  166.                     values.Add(new KeyValuePair<int, double>(0, powResult.Value));
  167.                     index = powResult.Key;
  168.                 }
  169.                 index++;
  170.             }
  171.  
  172.             return values;
  173.         }
  174.  
  175.         static double Calculate(string expression)
  176.         {
  177.             List<KeyValuePair<int, double>> values = ReversePolishNotation(expression);
  178.             Stack<double> dynamicResult = new Stack<double>();
  179.  
  180.             double result = 0.0d;
  181.  
  182.             int index = 0;
  183.             while (index < values.Count)
  184.             {
  185.                 if (values[index].Key == 1)
  186.                 {
  187.                     double secondValue = dynamicResult.Pop();
  188.                     double firstValue = dynamicResult.Pop();
  189.  
  190.                     char arithmeticOperator = (char)values[index].Value;
  191.                     switch (arithmeticOperator)
  192.                     {
  193.                         case '+': dynamicResult.Push(firstValue + secondValue); break;
  194.                         case '-': dynamicResult.Push(firstValue - secondValue); break;
  195.                         case '*': dynamicResult.Push(firstValue * secondValue); break;
  196.                         case '/': dynamicResult.Push(firstValue / secondValue); break;
  197.                     }
  198.                 }
  199.                 else
  200.                 {
  201.                     dynamicResult.Push(values[index].Value);
  202.                 }
  203.                 index++;
  204.             }
  205.            
  206.             if (dynamicResult.Count > 0)
  207.             {
  208.                 result = dynamicResult.Pop();
  209.             }
  210.  
  211.             return result;
  212.         }
  213.  
  214.         static void Main(string[] args)
  215.         {
  216.             string expression = Console.ReadLine();
  217.             expression = expression.Replace(" ", String.Empty);
  218.  
  219.             double result = Calculate(expression);
  220.             Console.WriteLine(result);
  221.         }
  222.     }
  223. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement