Exemplo n.º 1
0
        public void GreaterThan()
        {
            RPN test = new RPN("5 > 2").Compute();

            PostFix math = new PostFix(test);

            Assert.AreEqual(1, math.Compute());

            test.SetEquation("5 > 10").Compute();

            math = new PostFix(test);
            Assert.AreEqual(0, math.Compute());

            test.SetEquation("5 >= 5").Compute();

            math = new PostFix(test);
            Assert.AreEqual(1, math.Compute());

            test.SetEquation("15 >= 5").Compute();

            math = new PostFix(test);
            Assert.AreEqual(1, math.Compute());

            test.SetEquation("5 >= 15").Compute();

            math = new PostFix(test);
            Assert.AreEqual(0, math.Compute());
        }
Exemplo n.º 2
0
        public void powerOperator()
        {
            RPN     test = new RPN("(2/2)^1").Compute();
            PostFix math = new PostFix(test);

            Assert.AreEqual(1, math.Compute());
        }
Exemplo n.º 3
0
        public RPN CreateRPN(string expr)
        {
            RPN rpn = new RPN(expr);

            rpn.CreateAst();
            return(rpn);
        }
Exemplo n.º 4
0
        // We call it after correct input field text
        public void OnValueChangeInputField()
        {
            BInputField bInputField = inputField.GetComponent <BInputField> ();

            // Yes, It is a little bit dirty, but It is simple and it works :)
            if (!bInputField.doNotHandleEvent)
            {
                var str = inputField.text;

                // Getting the clear string - without the result (anwer) part
                str = BInputField.RemoveTextAfterEqual(str);

                str = str.Trim();

                var d = RPN.Calculate(str);

                // We show a result if we have it and if result is not the input string
                if (IsResult(str, d))
                {
                    str += " = " + d.ToString();
                }

                // We are preventing loop on value change
                bInputField.doNotHandleEvent = true;
                inputField.text = str;
                bInputField.doNotHandleEvent = false;
            }
        }
Exemplo n.º 5
0
        private bool Check_LastSymb(object sender)
        {
            char ch = char.Parse((sender as Button).Tag.ToString());

            if (RPN.IsOperand(ch) || RPN.IsSpecSymb(ch) || Char.IsDigit(ch))
            {
                if (textbox.Text != "")
                {
                    char[] txt = textbox.Text.ToCharArray();
                    if (!RPN.IsOperand(txt[txt.Length - 1]))
                    {
                        return(true);
                    }
                    if (RPN.IsSpecSymb(ch) || Char.IsDigit(ch))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (Char.IsDigit(ch))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 6
0
        private void Check_LastSymb(object sender, KeyPressEventArgs e)
        {
            char number = e.KeyChar;

            e.Handled = true;
            if (RPN.IsOperand(number) || RPN.IsSpecSymb(number) || Char.IsDigit(number) || number == 8)
            {
                if (textbox.Text != "")
                {
                    char[] txt = textbox.Text.ToCharArray();
                    if (!RPN.IsOperand(txt[txt.Length - 1]))
                    {
                        e.Handled = false;
                    }
                    if (RPN.IsSpecSymb(number) || Char.IsDigit(number))
                    {
                        e.Handled = false;
                    }
                    if (number == 8)
                    {
                        e.Handled = false;
                    }
                }
                else
                {
                    if (Char.IsDigit(number))
                    {
                        e.Handled = false;
                    }
                }
            }
        }
Exemplo n.º 7
0
 private void button1_Click(object sender, EventArgs e)
 {
     valuesGrid.Columns.Clear();
     //Reading new function
     try
     {
         rpnFunction = RPN.toRPN(functionBox.Text);
     }
     catch (Exception)
     {
         MessageBox.Show("Ошибка, неверно записана формула", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     //Finding all variables in function
     vs = RPN.findAllX(rpnFunction);
     //Displaying grid for entering variables values
     if (vs.Count != 0)
     {
         foreach (string value in vs)
         {
             valuesGrid.Columns.Add("", value);
         }
         valuesGrid.Rows.Add();
     }
     valuesGrid.AllowUserToAddRows = false;
 }
Exemplo n.º 8
0
        // Method to perform search on the querey
        private void search(RPN rpn, Fleet fleet)
        {
            Console.WriteLine("\n--------------------------------------------- Searching available vehicles ---------------------------------------------");

            // Create new datatable for available vehicles (unrented)
            DataTable AvaiableVehicles = new DataTable();

            // Fill table for available vehicles
            CsvOperations.SearchToTable(fleet, AvaiableVehicles);
            // Show search to table datatable
            CsvOperations.ShowDataTable(AvaiableVehicles, fleet.FleetFile, "ASCII", true);

            Console.Write("\nInfix expression:    ");
            foreach (string token in rpn.InfixTokens)
            {
                Console.Write(token + " ");
            }
            Console.WriteLine();

            Console.Write("Postfix expression:  ");
            foreach (string token in rpn.PostfixTokens)
            {
                Console.Write(token + " ");
            }
            Console.WriteLine();
            Console.WriteLine();

            fleet.search(out string[] result, rpn);

            if (result.Length == 0)
            {
                throw new Exception("No match found");
            }

            List <string> results = new List <string>();

            foreach (string res in result)
            {
                // display vehicle by registration plate (rego)
                Vehicle v;
                for (int i = 0; i < fleet.vehicles.Count; i++)
                {   // go through, find the vehicle by rego
                    v = (Vehicle)fleet.vehicles[i];
                    if (v.registration == res)
                    {
                        results.Add(v.ToCSVstring());
                        break;
                    }
                }
            }

            Console.WriteLine("\n-------------------------------------------------- Query Search Output -------------------------------------------------");
            // Create new datatable for query result for searched vehicles
            DataTable resultTable = new DataTable();

            // fill query result table
            CsvOperations.SearchToTable(fleet, resultTable, results);
            // show datatable
            CsvOperations.ShowDataTable(resultTable, fleet.FleetFile, "Extended", true);
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
0
    // For testing. Don't modify.
    public static void Main(string[] args)
    {
        string test = Console.ReadLine();

        if (test == "rpn")
        {
            var rpn = new RPN();
            while (true)
            {
                string userInput = Console.ReadLine();
                if (userInput == "end")
                {
                    break;
                }
                else
                {
                    rpn.Process(userInput);
                    Console.WriteLine("=" + rpn.Result());
                }
            }
        }

        if (test == "remove_max")
        {
            var s1 = new Stack <int>();
            Console.ReadLine()
            .Split(new[] { ',' })
            .Select(Int32.Parse).ToList()
            .ForEach(n => s1.Push(n));

            Console.WriteLine(RemoveMax(ref s1));
            Console.WriteLine(
                string.Join(",", s1.Reverse().Select(i => i.ToString()).ToArray()));
        }
    }
Exemplo n.º 11
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}");
            }
        }
Exemplo n.º 12
0
        public void ImprovedEulersTests(double expected, double step, double iterations, string function, double x, params double[] y)
        {
            Queue <Element> calculated = RPN.SYA(function);
            double          value      = DiffEquations.ImprovedEulers(calculated, step, x, y.ToList(), (int)iterations);

            Assert.AreEqual(expected, value, 1e-3);
        }
Exemplo n.º 13
0
        public IActionResult CalculateX(string formula, double?x)
        {
            if (formula == null || x == null)
            {
                var bad2 = new {
                    status = "error",
                    result = "wrong input!"
                };
                return(BadRequest(bad2));
            }

            RPN rpn = new RPN(formula, (double)x);

            if (rpn.CheckInput())
            {
                var good = new {
                    status = "ok",
                    result = rpn.CalculateValueOfGivenX()
                };
                return(Ok(good));
            }
            var bad = new {
                status = "error",
                result = rpn.Message()
            };

            return(BadRequest(bad));
        }
Exemplo n.º 14
0
Arquivo: AST.cs Projeto: 65001/AbMath
        public void VariableAdditionExponent()
        {
            //TODO: Normalize
            RPN rpn = new RPN("x - x^2").Compute();

            Assert.AreEqual("x x 2 ^ -", rpn.Polish.Print());
        }
Exemplo n.º 15
0
        public void VariableContains()
        {
            RPN test = new RPN("x * 2").Compute();

            Assert.AreEqual("2 x *", test.Polish.Print());
            Assert.AreEqual(true, test.Data.ContainsVariables);
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
        public void Mul()
        {
            RPN rpn = new RPN();

            Assert.AreEqual(10, rpn.Proc("2*5"));
            Assert.AreEqual(10, rpn.Proc("2×5"));
        }
Exemplo n.º 18
0
        public IActionResult  Get(string formula)
        {
            if (string.IsNullOrEmpty(formula))
            {
                var data = new {
                    status  = "error",
                    message = "Please enter the formula!"
                };
                return(BadRequest(data));
            }
            RPN onp = new RPN(formula);

            if (onp.IsCorrect() == "true")
            {
                var data = new {
                    status = "ok",
                    result = new {
                        infix   = onp.Tokens().ToArray(),
                        postfix = onp.InfixToPostfix(onp.Tokens())
                    }
                };
                return(Ok(data));
            }
            else
            {
                var data = new {
                    status  = "error",
                    message = onp.IsCorrect()
                };
                return(BadRequest(data));
            }
        }
Exemplo n.º 19
0
        public void EulersTests(double expected, double step, double x, double y, double iterations, string function)
        {
            Queue <Element> calculated = RPN.SYA(function);
            double          value      = DiffEquations.Eulers(calculated, step, x, y, (int)iterations);

            Assert.AreEqual(expected, value, 1e-3);
        }
Exemplo n.º 20
0
        public IActionResult CalculateInterval(string formula, double?from, double?to, int?n)
        {
            if (formula == null || from == null || to == null || n == null)
            {
                var bad2 = new {
                    status = "error",
                    result = "wrong input"
                };
                return(BadRequest(bad2));
            }

            RPN rpn = new RPN(formula, (double)from, (double)to, (int)n);

            if (rpn.CheckInput())
            {
                var good = new {
                    status = "ok",
                    result = rpn.CalculateValueOfGivenInterval()
                };
                return(Ok(good));
            }
            var bad = new {
                status = "error",
                result = rpn.Message()
            };

            return(BadRequest(bad));
        }
Exemplo n.º 21
0
Arquivo: AST.cs Projeto: 65001/AbMath
        public void Swap()
        {
            //TODO: Normalize
            RPN rpn = new RPN("x^@ + x - x^@ - x").Compute();

            Assert.AreEqual("x @ ^ x + x @ ^ - x -", rpn.Polish.Print());
        }
        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)));
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        public async Task EvalTest()
        {
            RPN rpn = new RPN();

            Console.Write("Type infix expression [ctrl+c to brake]: ");
            string infix = "AX = 5 + 90";
            string lol   = rpn.Eval(infix).Content;
        }
Exemplo n.º 25
0
 static void Main(string[] args)
 {
     while (true)                                              //Бесконечный цикл
     {
         Console.Write("Input: ");                             //Предлагаем ввести выражение
         Console.WriteLine(RPN.Calculate(Console.ReadLine())); //Считываем, и выводим результат
     }
 }
Exemplo n.º 26
0
        public void Quart()
        {
            RPN rpn = new RPN();

            Assert.AreEqual((1 + 2) * 3, rpn.Proc("(1+2)*3"));
            Assert.AreEqual((1.0 + 2.0) * 3.0 / 4.0, rpn.Proc("(1+2)*3/4"));
            Assert.AreEqual(1 + 2 * (3 + 4) * 5, rpn.Proc("1+2*(3+4)*5"));
        }
Exemplo n.º 27
0
        public void UnaryDecimal()
        {
            RPN test = new RPN("-.5 + .5").Compute();

            PostFix math = new PostFix(test);

            Assert.AreEqual(0, math.Compute());
        }
Exemplo n.º 28
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string expr   = this.TextBox1.Text;
            RPN    rpn    = new RPN();
            int    result = rpn.calculate(expr);

            this.TextBox2.Text = result.ToString();
        }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
0
        public void UnarySubtract2()
        {
            RPN test = new RPN("5 + -2").Compute();

            PostFix math = new PostFix(test);

            Assert.AreEqual(3, math.Compute());
        }
 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();
     }
 }