예제 #1
0
        public Expression ToPolskExpression()
        {
            var res   = new Expression();
            var stack = new YourStack <ExpressionPart>(Elements.Count);

            foreach (var el in Elements)
            {
                switch (el.Type)
                {
                case ExpressionPartType.OpenBracket:
                    stack.Push(el);
                    continue;

                case ExpressionPartType.CloseBracket:
                    while (!stack.IsEmpty)
                    {
                        if (stack.Peek().Type == ExpressionPartType.OpenBracket)
                        {
                            stack.Pop();
                            break;
                        }
                        res.Elements.Add(stack.Pop());
                    }
                    continue;

                case ExpressionPartType.Number:
                    res.Elements.Add(el);
                    continue;

                case ExpressionPartType.OrdinaryOperation:
                case ExpressionPartType.BinaryOperation:
                    if (stack.IsEmpty)
                    {
                        stack.Push(el);
                    }
                    else
                    {
                        while (true)
                        {
                            if (stack.IsEmpty || el.Rating > stack.Peek().Rating)
                            {
                                stack.Push(el);
                                break;
                            }
                            else
                            {
                                res.Elements.Add(stack.Pop());
                            }
                        }
                    }
                    continue;
                }
            }
            while (!stack.IsEmpty)
            {
                res.Elements.Add(stack.Pop());
            }
            return(res);
        }
예제 #2
0
        public double Calculate()
        {
            var exp   = ToPolskExpression();
            var stack = new YourStack <ExpressionPart>(exp.Elements.Count);

            foreach (var el in exp.Elements)
            {
                if (el.Type == ExpressionPartType.Number)
                {
                    stack.Push(el);
                }
                else if (el.Type == ExpressionPartType.BinaryOperation)
                {
                    var e2 = stack.Pop().Number;
                    var e1 = stack.Pop().Number;
                    stack.Push(new ExpressionPart(el.Operation.OperationFunction(e1, e2)));
                }
                else if (el.Type == ExpressionPartType.OrdinaryOperation)
                {
                    stack.Push(new ExpressionPart(el.Operation.OperationFunction(stack.Pop().Number)));
                }
            }
            return(stack.Pop().Number);
        }