public void Check() { Assert.Equal(new List <string>() { "1", "1", "+", "1", "-" }, ReversePolishNotation.Parse("1+1-1")); }
private void Calculate_button_Click(object sender, RoutedEventArgs e) { try { System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); customCulture.NumberFormat.NumberDecimalSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = customCulture; double result = 0.0; var rpn = new ReversePolishNotation(); rpn.Parse(Expression_textBox.Text.Replace(',', '.')); result = rpn.Evaluate(); var output = new StringBuilder(); output.AppendFormat("Original: {0}", rpn.OriginalExpression + Environment.NewLine); output.AppendFormat("Transition: {0}", rpn.TransitionExpression + Environment.NewLine); output.AppendFormat("Postfix: {0}", rpn.PostfixExpression + Environment.NewLine); output.AppendFormat("Result: {0}", result); Results_textBox.Text = output.ToString(); } catch (Exception ex) { Results_textBox.Text = ex.Message; } }
public ExpertSystemRule(string line) { Type = line.Contains("<=>") ? ImplicationType.EQUAL : ImplicationType.IMPLY; var notation = new ReversePolishNotation(); string[] separator = { "=>", "<=>" }; var lines = line.Split(separator, StringSplitOptions.RemoveEmptyEntries); if (lines.Length != 2) { throw new Exception("ESRule error convert! " + line); } NpiLeft = notation.Convert(lines[0]); NpiRight = notation.Convert(lines[1]); if (NpiRight.Contains("+!")) { throw new Exception("Format error!(right +!) " + line); } if (Type == ImplicationType.EQUAL && (NpiLeft.Contains('|') || NpiRight.Contains('|'))) { throw new Exception("Format error!(| and <=>) " + line); } if (Type == ImplicationType.EQUAL && (NpiLeft.Contains("+!") || NpiRight.Contains("+!"))) { throw new Exception("Format error!(+! and <=>) " + line); } }
static void Main() { Console.Write("Введите диапазон значений x по образцу (0 10): "); double[] rangeX = ReadInput(); Console.Write("Введите шаг построения функции: "); double[] step = ReadInput(); string path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); string inputFile = @"\input.txt"; string outputFile = @"\output.txt"; WorkWithFiles workWithFiles = new WorkWithFiles(); if (!File.Exists(path + inputFile)) { workWithFiles.WriteTextToFile(path, inputFile, "log(15^x^x - 25,5 + 5! * 43 - (7 * 5)) * cos(5) - 1"); } ReversePolishNotation reversePolishNotation = new ReversePolishNotation(); List <string> textExpression = workWithFiles.ReadTextFromFile(path, inputFile); List <object> parseExpression = reversePolishNotation.Parse(textExpression); foreach (var item in parseExpression) { Console.WriteLine(item); } ; TableOfFunctionValues tableOfFunctionValues = new TableOfFunctionValues(); string finalText = tableOfFunctionValues.CreatingTable(rangeX, step[1], parseExpression); workWithFiles.WriteTextToFile(path, outputFile, finalText); }
public void TestGetTypeError(Type expectedExceptionType, char c) { var notation = new ReversePolishNotation(); Assert.Throws(expectedExceptionType, () => notation.GetType(c)); }
private void StartCompile(object sender, RoutedEventArgs e) { ClearErrors(); Storage.Clear(); tbOutput.Clear(); var exprParser = new ReversePolishNotation(); var text = textEditor.Text + "\r\n"; try { exprParser.Interpret(text); } catch (SyntaxException ex) { Storage.Output = ex.Message; textEditor.TextArea.TextView.LineTransformers.Add(new LineColorizer( CalculateRow(ex.Lexem.Position), ex.Lexem.Position, ex.Lexem.Content.ToString().Length + ex.Lexem.Position)); } tbOutput.Text = Storage.Output; }
public void TestMethod10() { var expression = "-1 - 4 as int = 0 as int - 5 as int"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestMethod12() { var expression = "(1 * (-3)) + (5 - 8) * 3 + 0/2 = -12"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestMethod17() { var expression = "( 5 + 2 ) * 3 + 2 * ( 1 + 3 ) = 29"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestNull(Type expectedExceptionType, string str) { var notation = new ReversePolishNotation(); var newString = str; Assert.Throws(expectedExceptionType, () => notation.GetNextChar(ref newString, out _)); }
public void CheckNotation(string input, string expectedString) { var notation = new ReversePolishNotation(); var inputCopy = input.PreProcess(); var notationResult = notation.Convert(inputCopy); Assert.True(string.Equals(notationResult, expectedString)); }
public void TestMethod22() { var expression = "11 + 10 > 12 and \"3.5\" as double > 0.5"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestMethod30() { var expression = "\"12:12:12\" as timespan > \"12:12:10\" as timespan"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestMethod35() { var expression = "\"4 / 3 / 2007 2:23:57 AM\" as datetimeoffset = \"4 / 3 / 2007 2:23:57 AM\" as datetimeoffset'"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestMethod36() { var expression = "\"0E984725-C51C-4BF4-9960-E1C80E27ABA0\" as guid = \"0E984725-C51C-4BF4-9960-E1C80E27ABA0\" as guid"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void TestMethod9() { var expression = "-3 + 5 = 2"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens); Assert.AreEqual(t, true); }
public void Calculate(string expression, double a, double b, double c, double d, double e, string expected) { var exp = CreateNormalExpression(expression, a, b, c, d, e); var actual = ReversePolishNotation.Calculate(exp); expected = expected.Replace(".", ","); Assert.Equal(expected, actual.ToString("N3")); }
public void GetExpression_InputArgument_ReturnExpression() { //Arrange var expression = "4*2+2"; //Act var result = ReversePolishNotation.GetExpression(expression); //Assert Assert.AreEqual("4 2 * 2 + ", result); }
public void TestMethod7() { var expression = "1 + f = 3"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens, new Dictionary <string, object>() { { "f", 2 }, }); Assert.AreEqual(t, true); }
public void TestMethod129() { var expression = "\"12.12:12:12\" as timespan = f"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens, new Dictionary <string, object>() { { "f", new TimeSpan(12, 12, 12, 12) } }); Assert.AreEqual(t, true); }
public void Counting_InputArgument_ReturnResult() { //Arrange var expression = "4 2 * 2 + "; //Act var result = ReversePolishNotation.Counting(expression, new Number(), new Number()); //Assert Assert.AreEqual(10, result.Value); }
public void ConvertFromInfix_XEquXCompYAnd0f() { // Arrange var infix = "x = x ? y & 0f"; var expected = "x = x y 0f & ?"; // Act var actual = ReversePolishNotation.ConvertFromInfix(infix); // Assert Assert.AreEqual(expected, actual); }
public void ConvertFromInfix_XEquOpenParXCompYCloseParAnd0f() { // Arrange var infix = "x = ( x ? y ) & 0f"; var expected = "x = x y ? 0f &"; // Act var actual = ReversePolishNotation.ConvertFromInfix(infix); // Assert Assert.AreEqual(expected, actual); }
public void ConvertFromInfix_XEqu0fOrParenthesisXAndYParenthesis() { // Arrange var infix = "x = 0f | ( x & y )"; var expected = "x = 0f x y & |"; // Act var actual = ReversePolishNotation.ConvertFromInfix(infix); // Assert Assert.AreEqual(expected, actual); }
public void TestMethod26() { var expression = "f > z"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens, new Dictionary <string, object>() { { "f", new DateTime(2, 1, 1) }, { "z", new DateTime(1, 1, 1) } }); Assert.AreEqual(t, true); }
public void TestMethod23() { var expression = "f = z"; var tokens = ReversePolishNotation.GetTokens(expression); var t = ReversePolishNotation.Evaluate(tokens, new Dictionary <string, object>() { { "f", new byte[] { 1, 2 } }, { "z", new byte[] { 1, 2 } } }); Assert.AreEqual(t, true); }
public void ConvertFromInfix_XEquParenthesisXAndYParenthesisOr0f() { // Arrange var infix = "x = ( x & y ) | 0f"; var expected = "x = x y & 0f |"; // Act var actual = ReversePolishNotation.ConvertFromInfix(infix); // Assert Assert.AreEqual(expected, actual); }
static void Main(string[] args) { ReversePolishNotation notation = new ReversePolishNotation(); Console.Write("Okay, dude. Enter expression, ok?\n\t"); notation.Expression = Console.ReadLine(); // input expression; Console.WriteLine("\nReverse Polish Notation: \n\t{0}", notation.Expression); notation.InputValues(); Console.WriteLine("\nResult: {0}", notation.Result()); Console.ReadKey(); }
private void AddOperatorToStack(string @operator) { // Відкриваюча дужка "(" повинна мати найнижчий пріоритет, але записуватися в стек, нічого не виштовхуючи if (@operator == "(") { Stack.Push(new PolishNotation { Token = @operator, Type = PolishNotationTokenType.Operator }); return; } // 3. Якщо стек порожній, то поточна операція заноситься в стек if (Stack.Count == 0) { Stack.Push(new PolishNotation { Token = @operator, Type = PolishNotationTokenType.Operator }); return; } PolishNotation head = Stack.Peek(); string headToken = head.Token.StartsWith("if") ? "if" : head.Token.StartsWith("while") ? "while" : head.Token; // 2. Якщо пріоритет операції, що знаходиться в стеку, // не менший за пріоритет поточної вхідної операції, // то операція зі стека подається на вихід і п.2 повторюється, if (_operatorsPriorities[headToken] >= _operatorsPriorities[@operator]) { PolishNotation notation = Stack.Pop(); if (notation.Token != "(") // Причому "(" ніколи не передається на вихід { ReversePolishNotation.Add(notation); // операція зі стека подається на вихід } AddOperatorToStack(@operator); // п.2 повторюється return; } // інакше поточна операція заноситься в стек. if (@operator != ")") // Причому ")" ніколи не заноситься в стек { Stack.Push(new PolishNotation { Token = @operator, Type = PolishNotationTokenType.Operator }); } }
public static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; double result = 0.0; ReversePolishNotation rpn = new ReversePolishNotation(); // rpn.Parse("pow(2, 3.14) * (3 - (3 * sqrt(2) - 3.2) + 1.5*0.3)"); rpn.Parse("(3+5.3) * 2.7 - ln(22) / pow(2.2, -1.7)"); result = rpn.Evaluate(); Console.WriteLine("orig: {0}", rpn.OriginalExpression); Console.WriteLine("tran: {0}", rpn.TransitionExpression); Console.WriteLine("post: {0}", rpn.PostfixExpression); Console.WriteLine("result: {0}", result); }
static void Main() { ReversePolishNotation rpn = new ReversePolishNotation(); List<Tuple<string[], int>> testInputs = new List<Tuple<string[], int>>(); testInputs.Add(Tuple.Create(new string[] {"2", "1", "+", "3", "*"}, 9)); testInputs.Add(Tuple.Create(new string[] {"4", "13", "5", "/", "+"}, 6)); foreach (var input in testInputs) { if (rpn.Solve(input.Item1) != input.Item2) { WriteLine("Tests failed for {0}!", input.Item2); return; } } WriteLine("Tests passed!"); }
static void Main(string[] args) { Console.Write("Enter an expression: "); string expression = Console.ReadLine(); try { ReversePolishNotation rpn = new ReversePolishNotation(); rpn.Parse(expression); Console.WriteLine("Result: {0}", rpn.Evaluate()); } catch (Exception ex) { Console.WriteLine(ex.Message); } }