Esempio n. 1
0
    public bool TryEvaluate(string exp, out int value)
    {
        if (m_RPN.Parse(exp))
        {
            object result = m_RPN.Evaluate();
            if (result != null && int.TryParse(result.ToString(), out value))
            {
                return(true);
            }
        }

        Debug.LogError("解析表达式 " + exp + " 失败");
        value = 0;
        return(false);
    }
Esempio n. 2
0
        static void Main(string[] args)
        {
            var rootCommand = new RootCommand
            {
                new Argument <string>("expression", "RPN expression to be evaluated"),
                new Option <List <string> >(new string[] { "-p", "--parameters" }, description: "List of parameters (primitive or json)"),
                new Option <List <FileInfo> >(new string[] { "-f", "--files" }, description: "Files to be appended to parameters list"),
            };

            rootCommand.Description = "RPN Evaluator based on RPN.Net";

            rootCommand.Handler = CommandHandler.Create <string, List <string>, List <FileInfo> >((expression, parameters, files) =>
            {
                List <object> parsedParameters = ParseParameters(parameters, files);
                try
                {
                    var val = (RPN.Evaluate(new RPNExpression(expression, parsedParameters.ToArray())).ToString());
                    Console.WriteLine(val);
                    Environment.Exit(0);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Environment.Exit(1);
                }
            });

            rootCommand.InvokeAsync(args);
        }
Esempio n. 3
0
        static bool EvaluateFunction(RPNContext context)
        {
            if (context.Current.StartsWith("@@"))
            {
                var blockExpression = context.Blocks[context.Current];

                var value = RPN.Evaluate(blockExpression);
                context.Stack.Push(value);
                return(true);
            }
            else if (context.Current.StartsWith("@"))
            {
                var label = context.Current;
                var list  = new List <string>();

                context.MoveNext();
                while (context.Current != label)
                {
                    list.Add(context.Current);
                    context.MoveNext();
                }
                context.Blocks.Add("@" + label, new RPNExpression(String.Join(" ", list), context.Data.ToArray()));
                return(true);
            }
            return(false);
        }
        public static void Run()
        {
            Tokeniser    tokeniser = new Tokeniser(Console.ReadLine());
            List <Token> tokens    = tokeniser.Tokenise().ToList();

            TreeNode bin1 = TreeBuilder.BuildAST(tokens); // e.g "5 * 2 + 1" -> "5 2 * 1 +"

            // Using TreeNode type, not BinOp (Binary Operator) as we cannot guarantee the root node of the abstract syntax tree will be an operator.

            Console.WriteLine("To postfix:");
            foreach (TreeNode node in Traversal.postOrder(bin1))
            {
                Console.Write(node.value + " ");
            }
            Console.WriteLine("\nTo infix:");
            foreach (TreeNode node in Traversal.inOrder(bin1))
            {
                Console.Write(node.value + " ");
            }
            Console.WriteLine("\nTo prefix:");
            foreach (TreeNode node in Traversal.preOrder(bin1))
            {
                Console.Write(node.value + " ");
            }
            Console.WriteLine();

            // Now using reverse polish notation, calculate what the result is. This takes in a postfix-ordered list of TreeNodes.
            Console.WriteLine("Answer: " + RPN.Evaluate(Traversal.postOrder(bin1)));
        }
Esempio n. 5
0
        static void Test(string name, string exp, dynamic expected, params object[] objects)
        {
            _total++;
            string strVal = "";
            bool   status = false;

            try
            {
                var val = RPN.Evaluate(exp, objects);
                strVal = val.ToString();
                status = expected == val;

                if (status)
                {
                    _success++;
                }

                Console.WriteLine($"{name} => RPN: {exp} :: Expected: {expected} :: Value: {strVal} :: Test: {(status ? "PASS" : "FAIL")}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"{name} => RPN: {exp} :: Expected: {expected} :: Value: EXCEPTION :: Test: FAIL");
                Console.WriteLine($"          {e.Message}");
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 计算具体的费用
        /// </summary>
        /// <param name="costFormularKey"></param>
        /// <param name="salarySummary"></param>
        /// <returns></returns>
        private static decimal CalculateCostDetails(Guid costFormularKey, SalarySummaryEntity salarySummary)
        {
            decimal            result         = 0M;
            CostFormularEntity formularEntity = CostFormularBLL.Instance.Get(costFormularKey);

            if (formularEntity == null)
            {
                return(0M);
            }

            string formularValue = formularEntity.CostFormularValue;

            if (string.IsNullOrWhiteSpace(formularValue) == false)
            {
                List <string> costElementList = StringHelper.GetPlaceHolderList(formularValue, "{", "}");
                foreach (string costElement in costElementList)
                {
                    string placeHolderContent = string.Empty;
                    switch (costElement)
                    {
                    case "NeedPaySalary":
                        placeHolderContent = salarySummary.SalaryNeedPayBeforeCost.ToString();
                        break;

                    case "RealPaySalary":
                        placeHolderContent = salarySummary.SalaryNeedPayToLabor.ToString();
                        break;

                    default:
                    {
                        BasicSettingEntity basicSettingEntity = CostList.Find(w => w.SettingKey == costElement);
                        if (basicSettingEntity != null)
                        {
                            placeHolderContent = basicSettingEntity.SettingValue;
                        }
                        break;
                    }
                    }

                    string placeHolder = "{" + costElement + "}";
                    formularValue = formularValue.Replace(placeHolder, placeHolderContent);
                }

                try
                {
                    RPN rpn = new RPN();
                    if (rpn.Parse(formularValue))
                    {
                        result = Convert.ToDecimal(rpn.Evaluate());
                    }
                }
                catch
                {
                    result = 0;
                }
            }

            return(result);
        }
Esempio n. 7
0
        static void Summary()
        {
            var rate    = RPN.Evaluate("$0 $1 perc", _total, _success);
            var summary = $"Summary: Total: {_total}, Success: {_success}, Failures: {_total - _success}, Success Rate: {rate}%";

            Console.WriteLine("".PadLeft(80, '*'));
            Console.WriteLine(summary);
        }
 protected void Button1_Click(object sender, EventArgs e)
 {
     RPN rpn = new RPN();
     string inputData = this.TextBox1.Text;
     if (rpn.Parse(inputData) == true)
     {
         this.Button1.Text = rpn.Evaluate().ToString();
     }
 }
        public override void ActionExcute()
        {
            String strText = actionCalculateData.strExpression;
            bool   IsVar   = false;
            String item    = String.Empty;
            String tmpExp  = String.Empty;


            if (actionCalculateData.strExpression == String.Empty)
            {
                return;
            }

            foreach (char ch in strText)
            {
                Regex regex = new Regex(@"[~]{1}");
                if (IsVar && regex.IsMatch(item))
                {
                    Regex rg = new Regex(@"^[0-9]*[+,\-,\*,\/,&,|,=,>,<,(,),.,;]*$");
                    if (rg.IsMatch(ch.ToString()))
                    {
                        IsVar = false;
                        String strValue = GetValue(item);
                        tmpExp += strValue;
                        item    = String.Empty;
                    }
                }
                if (ch != '#' && !IsVar)
                {
                    if (ch != ';')
                    {
                        tmpExp += ch.ToString();
                    }
                }
                else
                {
                    IsVar = true;
                    if (ch != '#')
                    {
                        item += ch.ToString();
                    }
                }
            }



            RPN rpn = new RPN();

            if (rpn.Parse(tmpExp))
            {
                doubleValue = (double)rpn.Evaluate();
            }
        }
Esempio n. 10
0
        public string SolveFormula(string expression)
        {
            if (expression == "")
            {
                return("");
            }
            if (expression.Substring(0, 1) == "'")
            {
                return(expression.Replace("'", ""));
            }
            RPN rpn = new RPN();

            if (rpn.Parse(expression))
            {
                Stack <object> operandProcessed = new Stack <object>();
                object[]       tokens           = rpn.Tokens.ToArray();
                for (int i = tokens.Length - 1; i >= 0; i--)
                {
                    object item = (object)tokens[i];
                    if (item is Operator @operator)
                    {
                        operandProcessed.Push(@operator);
                    }
                    else
                    {
                        Operand operand = (Operand)item;
                        if (operand.Type == OperandType.STRING)
                        {
                            object tag = operand.Value;
                            if (IsSystemVariable((string)tag))
                            {
                                tag = CalculateSystemVariable((string)tag);
                            }
                            else
                            {
                                tag = GetTagsValue((string)tag);
                            }
                            operand.Value = tag;
                            operand.Type  = OperandType.NUMBER;
                        }
                        operandProcessed.Push((object)operand);
                    }
                }
                rpn.Tokens = operandProcessed;
            }
            return(rpn.Evaluate().ToString());
        }
Esempio n. 11
0
        public void Test(string name, string exp, dynamic expected, params object[] objects)
        {
            string strVal;
            bool   status;

            try
            {
                var val = RPN.Evaluate(new RPNExpression(exp, objects));
                strVal = val.ToString();
                status = expected == val;

                Assert.AreEqual(expected, val);
            }
            catch
            {
                throw;
            }

            Console.WriteLine($"{name} => RPN: {exp} :: Expected: {expected} :: Value: {strVal} :: Test: {(status ? "PASS" : "FAIL")}");
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            //var loggerFactory = LoggerFactory.Create(builder =>
            //{
            //    builder.AddConsole().SetMinimumLevel(LogLevel.Debug);
            //});
            //ILogger logger = loggerFactory.CreateLogger<Program>();

            //logger.LogError("This is log message.");
            //Thread.Sleep(1000);
            //return;

            if (args.Length == 0)
            {
                ShowExamples();
                return;
            }
            var expression = string.Join(' ', args);

            Console.WriteLine(RPN.Evaluate(expression, null));
        }
Esempio n. 13
0
        /// <summary>
        /// 画range
        /// </summary>
        /// <param name="range"></param>
        private void PaintRange(Range range, ReoGridControl grid, ref RPN rpn)
        {
            var sheet = grid.CurrentWorksheet;
            //合并单元格
            string _posString = range.Postion.TopLeft + ":" + range.Postion.BottomRight;
            var    _Gridrange = sheet.Ranges[_posString];

            _Gridrange.Merge();
            //设置range边框
            sheet.SetRangeBorders(_Gridrange, BorderPositions.Outside, new RangeBorderStyle
            {
                Color = unvell.ReoGrid.Graphics.SolidColor.Black,
                Style = BorderLineStyle.Solid,
            });
            //填充数据
            switch (range.RangeType)
            {
            case RANGETYPE.Text: _Gridrange.Data = range.FormulaOrText;
                //_Gridrange.Style.HorizontalAlign = ReoGridHorAlign.Center;
                //_Gridrange.Style.VerticalAlign = ReoGridVerAlign.Middle;
                break;

            case RANGETYPE.Calc:
                object value = rpn.Evaluate(range.FormulaOrText);
                _Gridrange.Data = value;
                sheet.SetRangeDataFormat(_Gridrange, CellDataFormatFlag.Number, range.NumberFormatArgs);
                break;

            default:
                _Gridrange.Data = range.FormulaOrText;
                break;
            }
            _Gridrange.Style.HorizontalAlign = range.HAlign;
            _Gridrange.Style.VerticalAlign   = range.VAlign;
            _Gridrange.Style.FontName        = range.Font;
            _Gridrange.Style.FontSize        = range.FontSize;
        }
Esempio n. 14
0
        public int RPN_Test(string expr)
        {
            var res = RPN.Evaluate(expr);

            return(res);
        }
Esempio n. 15
0
        public Token ResolveExpression(List <Token> expr) // TODO
        {
            Token toReturn = new Token("", "");

            // First, replace variable name references with their values.
            expr = VariablesToValues(expr);

            // Now check tokens are all the same type in the expression (except grammar tokens)

            string exprResultType = CheckTypes(expr); // This func will throw error if they aren't

            // exprResultType now stores the final expected type for when expression is resolved to one token
            // e.g 1 + 1 => resolves to 'number'
            // e.g "1" + "1" => resolves to 'string'

            if (exprResultType.Equals("string"))
            // Indicates that we are dealing with a string expression
            {
                // The only operation that can be done to strings in an expression is '+' for concat
                if (expr.Count == 1)
                {
                    toReturn = new Token("string", expr[0].Value());
                }
                // If there is only one token in the whole expression, it must just be a string
                // Therefore we can just return the string as it's 1 token
                else
                {
                    // We must be dealing with concatenation
                    if (!expr[0].Type().Equals("string"))
                    {
                        throw new SyntaxError();
                    }
                    // Concatenation expressions MUST start with a string
                    // e.g string x = + "Hello World"; will cause ERROR as expr starts with '+'

                    string finalResult = expr[0].Value(); // First string in expression
                    int    index       = 1;

                    while (index < expr.Count)
                    {
                        if (expr[index].Type().Equals("operator"))
                        {
                            if (expr[index].Value().Equals("+") && index < expr.Count - 1)
                            {
                                finalResult += expr[index + 1].Value(); // Add NEXT string to final result
                            }
                            else
                            {
                                throw new TypeMatchError();  // Cannot do any other operation than '+' on strings
                            }
                        }

                        index++;
                    }
                    toReturn = new Token("string", finalResult);
                }
            }
            else if (exprResultType.Equals("number"))
            // Indicates we are dealing with a mathematical expression
            {
                TreeNode root = TreeBuilder.BuildAST(expr);           // Create abstract syntax tree of mathematical expression

                int result = RPN.Evaluate(Traversal.postOrder(root)); // Calculate result of RPN algorithm calculation

                toReturn = new Token("number", result.ToString());
            }
            else
            {
                throw new SyntaxError();  // invalid expression type has somehow made it through, we cannot evaluate it so throw error.
            }
            return(toReturn);
        }