private void EvaluateNewCellValue(Cell currentCell) { /* Conversion Required */ if (currentCell.Text[0] != '=') { currentCell.Value = currentCell.Text; } else { /* Set value equal to another cell's value */ ExpressionTree expTree = new ExpressionTree(currentCell.Text.Substring(1)); List <string> variableList = expTree.GetVariableName(); /* Can assume that all variables will be cells in the form (A1, B2, etc.) for this Assignment */ foreach (string key in variableList) { int colNum = key[0] - 65; // convert ascii to index int rowNum = int.Parse(key[1].ToString()) - 1; if (double.TryParse(this.GetCell(rowNum, colNum).Value, out double value)) { expTree.SetVariable(key, value); } else { expTree.SetVariable(key, 0); } } currentCell.Value = expTree.Evaluate().ToString(); Console.WriteLine(currentCell.Value); } }
public void SetVariableMethod() { ExpressionTree tree = new ExpressionTree("x+y"); tree.SetVariable("x", 5.0); tree.SetVariable("y", 4.0); Assert.AreEqual("9", tree.Evaluate().ToString()); }
/// <summary> /// evaluate the the expression of the target cell. Find and set the value of each variable in the expression, /// then set the target cells dependencies. Finally, set the value of the target cell to the result of the /// evaluated expression tree. /// </summary> /// <param name="targetCell"></param> private void EvaluateExpression(SubCell targetCell) { string targetExpression = targetCell.Text.Substring(1); //grab entire expression except "=" ExpressionTree expressionTree = new ExpressionTree(targetExpression); //create expression tree try { if (expressionTree.Variables.Count == 1) { string variable = expressionTree.Variables.First(); int[] index = ConvertNameToLocation(variable); SubCell dependentCell = GetCell(index[0], index[1]); //get cell at name location if (dependencies.ContainsKey(targetCell) == false) { dependencies.Add(targetCell, new HashSet <SubCell>()); //create dependency Cell entry } dependencies[targetCell].Add(dependentCell); //add dependent cell hash value at key entry if (dependentCell.Value == dependentCell.Text) { targetCell.SetValue(dependentCell.Text); } if (VerifyNoCircleRef(targetCell)) { return; } } else { foreach (string variable in expressionTree.Variables) { int[] index = ConvertNameToLocation(variable); SubCell dependentCell = GetCell(index[0], index[1]); //get cell at name location if (dependencies.ContainsKey(targetCell) == false) { dependencies.Add(targetCell, new HashSet <SubCell>()); //create dependency Cell entry } dependencies[targetCell].Add(dependentCell); //add dependent cell hash value at key entry //if the dependent cell value is a constant (double) double result; if (double.TryParse(dependentCell.Value, out result)) { expressionTree.SetVariable(variable, result); } } //evaluate the expression tree, and set target cell value targetCell.SetValue(expressionTree.Evaluate().ToString()); } } catch { throw; //throw the exception to HandleCellExpressionChange() } }
/// <summary> /// this is a main method which has direct interaction with the user. /// </summary> /// <param name="args"> args.</param> public static void Main(string[] args) { string expression = "x+y"; // create an instance of ExpressionTree class. ExpressionTree tree = new ExpressionTree(expression); // set varname and varVal to empty. string varName = string.Empty; string varVal = string.Empty; do { Console.WriteLine("Menu (current expression =" + tree.InFixExpression + ")"); MenuOption(); string userInput = Console.ReadLine(); Console.WriteLine(); switch (userInput) { case "1": // get a new expression and display the new expression Console.WriteLine("Enter new epression: "); tree = new ExpressionTree(Console.ReadLine()); break; case "2": // reads the vraible name and varible value. Console.WriteLine("Enter variable name:"); varName = Console.ReadLine(); Console.WriteLine("Enter variable value:"); string varValue = Console.ReadLine(); // if variable name is in the dictionary set new value to that otherwise add variable // name and value pair in the dictionary tree.SetVariable(varName, Convert.ToDouble(varValue)); break; case "3": // evaluate the result of the expression. Console.WriteLine(tree.Evaluate()); break; case "4": System.Environment.Exit(0); break; default: Console.WriteLine("Invalid option. Try again"); break; } }while (true); }
// post: displays a menu of options for the user to evaluate a given expression or enter their own public static void Main(string[] args) { string userInput = "0"; ExpressionTree tree = new ExpressionTree("A1-12-C1"); while (userInput != "4") { StringBuilder menu = new StringBuilder(); menu.AppendLine("Menu (current expression = \"" + tree.expression + "\")"); menu.AppendLine(" 1 = Enter a new expression"); menu.AppendLine(" 2 = Set a variable value"); menu.AppendLine(" 3 = Evaluate Tree"); menu.AppendLine(" 4 = Quit"); Console.WriteLine(menu); userInput = Console.ReadLine(); switch (userInput) { case "1": Console.WriteLine("Enter new expression: "); string expression = Console.ReadLine(); tree = new ExpressionTree(expression); break; case "2": Console.Write("Enter variable name: "); string varName = Console.ReadLine(); Console.Write("Enter variable value: "); string varValue = Console.ReadLine(); double num; while (!double.TryParse(varValue, out num)) { Console.Write("Enter variable value: "); varValue = Console.ReadLine(); } tree.SetVariable(varName, num); break; case "3": Console.WriteLine(tree.Evaluate()); break; } } }
/// <summary> /// Updates the spreadsheet. /// </summary> /// <param name="sender">The sending object.</param> /// <param name="e">A property changed event arguments.</param> private void Sheet_PropertyChanged(object sender, PropertyChangedEventArgs e) { try { if (!e.PropertyName.Contains("bgcolor")) { int row = Convert.ToInt32(e.PropertyName.Split(' ')[0]); int column = Convert.ToInt32(e.PropertyName.Split(' ')[1]); Cell cell = this.Cells[row, column]; // Check to see if cell evaluation is necessary. if (cell.Text.StartsWith("=")) { // Check for a self-reference. if (cell.Text.Contains(((char)(column + 65)).ToString() + (row + 1)) || cell.Text.Contains(((char)(column + 97)).ToString() + (row + 1))) { this.CellPropertyChanged.Invoke(this, new PropertyChangedEventArgs(e.PropertyName + " SELF_REFERENCE")); // Call CellPropertyChanged methods in Form1. return; } string expression = cell.Text.Substring(1); ExpressionTree et = new ExpressionTree(expression); et = new ExpressionTree(expression); string[] expArr = expression.Split(et.Operators, StringSplitOptions.None); // Check the length of the expression array. if (expArr.Length == 1) { if (this.CircularReferenceCheck(this.GetCell(row, column), this.GetCell(expArr[0]))) { this.CellPropertyChanged.Invoke(this, new PropertyChangedEventArgs(e.PropertyName + " CIRCULAR_REFERENCE")); return; } this.GetCell(expArr[0]).DependencyChanged += this.Dependency_PropertyChanged; this.GetCell(expArr[0]).AddDependency(cell); cell.Value = this.GetCell(expArr[0]).Value; } else { foreach (string s in expArr) { foreach (char c in s) { if (c < 48 || c > 57) { if (this.CircularReferenceCheck(this.GetCell(row, column), this.GetCell(s))) { this.CellPropertyChanged.Invoke(this, new PropertyChangedEventArgs(e.PropertyName + " CIRCULAR_REFERENCE")); return; } et.SetVariable(s, Convert.ToDouble(this.GetCell(s).Value)); if (!e.PropertyName.Contains("RESET")) { this.GetCell(s).DependencyChanged += this.Dependency_PropertyChanged; this.GetCell(s).AddDependency(cell); } break; } } } cell.Value = et.Evaluate().ToString(); } } else { cell.Value = cell.Text; } } this.CellPropertyChanged.Invoke(this, e); // Call CellPropertyChanged methods in Form1. } catch (Exception) { // Bad reference detected! this.CellPropertyChanged.Invoke(this, new PropertyChangedEventArgs(e.PropertyName + " BAD_REFERENCE")); // Call CellPropertyChanged methods in Form1. } }