Ejemplo n.º 1
0
        public string ToOPN()
        {
            string       finalOPNExpression = String.Empty;
            Stack <char> operationsStack    = new Stack <char>();

            for (int i = 0; i < _expression.Length; i++)
            {
                if (Char.IsDigit(_expression[i]))
                {
                    finalOPNExpression += _expression[i];
                    continue;
                }
                if (_expression[i] == '(')
                {
                    operationsStack.Push(_expression[i]);
                    continue;
                }
                if (_expression[i] == ')')
                {
                    while (operationsStack.Peek() != '(')
                    {
                        finalOPNExpression += operationsStack.Pop();
                    }
                    operationsStack.Pop();
                    continue;
                }
                if (_operationService.GetOperationByName(_expression[i]) != null)
                {
                    while ((operationsStack.Count > 0) && (_operationService.GetOperationByName(operationsStack.Peek()).Priority <= _operationService.GetOperationByName(_expression[i]).Priority))
                    {
                        finalOPNExpression += operationsStack.Pop();
                    }
                    operationsStack.Push(_expression[i]);
                    continue;
                }
            }

            while (operationsStack.Count > 0)
            {
                finalOPNExpression += operationsStack.Pop();
            }
            return(finalOPNExpression);
        }
        public double CalculateByOPN(string expressionOPN)
        {
            Stack <string> calculationsStack = new Stack <string>();

            for (int i = 0; i < expressionOPN.Length; i++)
            {
                if (Char.IsDigit(expressionOPN[i]))
                {
                    calculationsStack.Push(expressionOPN[i].ToString());
                    continue;
                }
                if (_operationService.GetOperationByName(expressionOPN[i]) != null)
                {
                    double b      = Convert.ToDouble(calculationsStack.Pop());
                    double a      = Convert.ToDouble(calculationsStack.Pop());
                    double result = _operationService.GetOperationByName(expressionOPN[i]).ApplyTo(a, b);
                    calculationsStack.Push(result.ToString());
                    continue;
                }
            }
            return(Convert.ToDouble(calculationsStack.Pop()));
        }