//Resolves only the provided operators private static List <MathElement> ResolveOperators(List <MathElement> problem, string[] operators) { for (var i = 0; i < problem.Count; i++) { var element = problem[i]; if (element.IsOperator && operators.Contains(element.Operator)) { var result = OperateOperators(problem[i - 1], element, problem[i + 1]); problem[i - 1] = new MathElement(result); problem.RemoveRange(i, 2); i--; } } return(problem); }
public static double DoMath(string input) { var problem = StringToProblem(input); //Resolve the Parenthesis deepest first one at a time. while (DeepestNestedProblem(problem).Success) { var(_, start, length) = DeepestNestedProblem(problem); var result = ResolveProblem(problem.GetRange(start + 1, length - 1)); problem[start] = new MathElement(result); // replace the ( of the nested statement with the result of the problem problem.RemoveRange(start + 1, length); //remove everything past the opening ( from the list } //Resolve the final unparenthesized problem return(ResolveProblem(problem)); }
private static List <MathElement> StringToProblem(string input) { var problem = new List <MathElement>(); var number = ""; for (var i = 0; i < input.Length; i++) { //is it a digit or a ., remember it var symbol = input[i]; if (IsDigit(symbol) || symbol == '.') { number += symbol; } //is not a digit or a . then add any remember digits and. to the problem as a number and clear the remembered ones if (!(IsDigit(symbol) || symbol == '.') && !string.IsNullOrWhiteSpace(number)) { var element = new MathElement(number); problem.Add(element); number = ""; } //its not a digit or a . so it must be a symbol to add to the problem if (!(IsDigit(symbol) || symbol == '.') && !string.IsNullOrWhiteSpace(symbol.ToString())) { var element = new MathElement(symbol); problem.Add(element); } } //Trailing number if (!string.IsNullOrWhiteSpace(number)) { var element = new MathElement(number); problem.Add(element); } return(problem); }
private static double OperateOperators(MathElement valA, MathElement op, MathElement valB) { return(OperateOperators(valA.Value, op.Operator, valB.Value)); }