public static long GetExpressionStringValue( string expressionString, MathRules rules) { long result; expressionString = expressionString.Trim(); if (Regex.IsMatch(expressionString, @"^\d+$")) { result = long.Parse(expressionString); } else { var topLevelOperatorIndexes = GetTopLevelOperatorIndexes(expressionString); var termExpressionStrings = GetTermExpressionStrings( expressionString, topLevelOperatorIndexes); var termExpressionStringValues = termExpressionStrings .Select(s => GetExpressionStringValue(s, rules)) .ToList(); var operators = GetOperators( expressionString, topLevelOperatorIndexes); result = GetExpressionValue( termExpressionStringValues, operators, rules); } return(result); }
public static long GetExpressionValue( IList <long> termValues, IList <MathOperator> operators, MathRules rules) { if (termValues.Count != operators.Count + 1) { throw new Exception($"Invalid term/operator counts"); } while (operators.Count > 0) { EvaluatePrimaryOperator(termValues, operators, rules); } return(termValues[0]); }
public static void EvaluatePrimaryOperator( IList <long> termValues, IList <MathOperator> operators, MathRules rules) { var operatorIndex = 0; if (rules.IsPerformingAdditionBeforeMultiplication) { for (int i = 0; i < operators.Count; i++) { var testOperator = operators[i]; if (MathOperator.Addition.Equals(testOperator)) { operatorIndex = i; break; } } } var expressionOperator = operators[operatorIndex]; var leftValue = termValues[operatorIndex]; var rightValue = termValues[operatorIndex + 1]; long resultValue = 0; if (MathOperator.Addition.Equals(expressionOperator)) { resultValue = leftValue + rightValue; } else if (MathOperator.Multiplication.Equals(expressionOperator)) { resultValue = leftValue * rightValue; } termValues.RemoveAt(operatorIndex); termValues.RemoveAt(operatorIndex); termValues.Insert(operatorIndex, resultValue); operators.RemoveAt(operatorIndex); }