Example #1
0
        public Queue <string> Parse(string mathematicalExpression)
        {
            var operatorStack = new Stack <OperatorMetadata>();
            var outputQueue   = new Queue <string>();

            string accumulatingNumber = string.Empty;

            foreach (char character in mathematicalExpression)
            {
                if (OperatorManifest.IsOperator(character))
                {
                    outputQueue.Enqueue(accumulatingNumber);
                    accumulatingNumber = string.Empty;
                    OperatorMetadata operatorMetadata = OperatorManifest.Parse(character);

                    while (operatorStack.Count > 0 && operatorStack.Peek().Priority >= operatorMetadata.Priority)
                    {
                        OperatorMetadata poppedOperator = operatorStack.Pop();
                        outputQueue.Enqueue(poppedOperator.Symbol);
                    }

                    operatorStack.Push(operatorMetadata);
                }
                else
                {
                    accumulatingNumber += character;
                }
            }

            if (!string.IsNullOrEmpty(accumulatingNumber))
            {
                outputQueue.Enqueue(accumulatingNumber);
            }

            while (operatorStack.Count > 0)
            {
                outputQueue.Enqueue(operatorStack.Pop().Symbol);
            }

            return(outputQueue);
        }
        public string Compute(string mathematicalExpression)
        {
            Console.WriteLine($"Executing computation for {mathematicalExpression}");

            // Convert from infix to postfix format
            Queue <string> postfixQueue = _parser.Parse(mathematicalExpression);

            Console.WriteLine($"Postfix string: {string.Join(":", postfixQueue)}");

            Stack <double> operands = new Stack <double>();

            try
            {
                foreach (string token in postfixQueue)
                {
                    if (OperatorManifest.IsOperator(token))
                    {
                        ICalculation calculation   = _calculationFactory.CreateCalculation(token);
                        double       secondOperand = operands.Pop();
                        double       firstOperand  = operands.Pop();
                        double       result        = calculation.Compute(firstOperand, secondOperand);
                        operands.Push(result);
                    }
                    else
                    {
                        operands.Push(string.IsNullOrEmpty(token) ? 0 : double.Parse(token));
                    }
                }

                double finalResult = operands.Count > 0 ? operands.Pop() : 0;
                return(finalResult.ToString());
            }
            catch (OverflowException)
            {
                throw new CalculatorException(ErrorCode.Overflow);
            }
        }