private decimal Calculate(List <ICalulatorNode> opreationList) { if (opreationList.OfType <CalculatorOperationNode>().Any(el => el.Token == MathToken.OpenBrackets)) { CalculateBraces(opreationList); } while (opreationList.OfType <CalculatorOperationNode>().Any(on => on.Token == MathToken.Multiply || on.Token == MathToken.Divide)) { RecalculateIndex(opreationList); var calculatorOperationNode = opreationList.OfType <CalculatorOperationNode>().First(on => @on.Token == MathToken.Multiply || @on.Token == MathToken.Divide); var Index = calculatorOperationNode.Index; var firstValue = ((CalulatorValueNode)opreationList[Index - 1]).Value; var operationValue = ((CalulatorValueNode)opreationList[calculatorOperationNode.Index + 1]).Value; firstValue = PerformOperation(firstValue, calculatorOperationNode.Token, operationValue); opreationList.RemoveAt(Index + 1); opreationList.RemoveAt(Index); opreationList[Index - 1] = new CalulatorValueNode(firstValue, Index - 1); RecalculateIndex(opreationList); } var result = ((CalulatorValueNode)opreationList[0]).Value; opreationList.RemoveAt(0); while (opreationList.Count != 0) { var operation = ((CalculatorOperationNode)opreationList[0]).Token; var operationValue = ((CalulatorValueNode)opreationList[1]).Value; result = PerformOperation(result, operation, operationValue); opreationList.RemoveAt(0); opreationList.RemoveAt(0); } return(result); }
public List <ICalulatorNode> Parse(string input) { var calulatorNodes = new List <ICalulatorNode>(); //macthes both : and / as divide symbol string Pattern = @"[\d]+|[\*\+\(\)\-\/\:]"; Regex rex = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection matches = rex.Matches(input); int index = 0; foreach (Match match in matches) { int parsedresult; var tryParse = int.TryParse(match.Value, out parsedresult); if (tryParse) { if (CheckIFMinus(calulatorNodes)) { calulatorNodes[index - 1] = new CalulatorValueNode(-parsedresult, index - 1); } else { calulatorNodes.Add(new CalulatorValueNode(parsedresult, index)); index++; } } else { MathToken token = ParseToken(match.Value); calulatorNodes.Add(new CalculatorOperationNode(token, index)); index++; } } return(calulatorNodes); }