Ejemplo n.º 1
0
        public Operand[] GetExpression(Queue <string> rpnQueue)
        {
            var stack = new Stack <Operand>();

            while (rpnQueue.Count > 0)
            {
                var s = rpnQueue.Dequeue();

                if (decimal.TryParse(s, out var d))
                {
                    stack.Push(new Operand {
                        Type = OperandType.Constant, Value = d
                    });
                }
                else if (operators.Contains(s))
                {
                    var op1 = stack.Pop();
                    var op2 = stack.Pop();

                    var opType = OperationType.FromValue <OperationType>(s);
                    if (opType == OperationType.Substract)
                    {
                        op1.Value = -op1.Value;
                        opType    = OperationType.Add;
                    }

                    if (op1.Operation?.OperationType == opType)
                    {
                        op1.Operation.Operands.Add(op2);
                        stack.Push(op1);
                    }
                    else if (op2.Operation?.OperationType == opType)
                    {
                        op2.Operation.Operands.Add(op1);
                        stack.Push(op2);
                    }
                    else
                    {
                        var op = new Operand
                        {
                            Type      = OperandType.Operation,
                            Operation = new Operation
                            {
                                OperationType = opType,
                                Operands      = new List <Operand> {
                                    op2, op1
                                }
                            },
                            Value = 1
                        };

                        stack.Push(op);
                    }
                }
                else
                {
                    stack.Push(new Operand {
                        Type = OperandType.Variable, Name = s, Value = 1
                    });
                }
            }

            return(stack.ToArray());
        }