private bool ReplaceWithSubtotal(int subtotal, int index) { calcArgsList.RemoveAt(index + 1); calcArgsList.RemoveAt(index); calcArgsList.RemoveAt(index - 1); CalculatorArgument newArg = new CalculatorArgument(index - 1, subtotal.ToString()); calcArgsList.Insert(index - 1, newArg); return(true); }
/// <summary> /// Perform Divide Multiply math operations (* /) first then Add Subtract (+ -) operations next /// If we already did /* operation, removed the existing arguments and inserted the result /// then we have to shift the index down by 2 to get to the next arguments that need to be /// operated on /// </summary> /// <returns> Returns the Integer result of the calculation </returns> public int calculateResult() { printCalcArgsList("Before"); bool wasReplaced = false; foreach (KeyValuePair <int, string> element in divMulOps) { int index = 0; if (wasReplaced) { index = element.Key - 2; } else { index = element.Key; } string multDivOp = element.Value; CalculatorArgument argNum1 = calcArgsList[index - 1]; CalculatorArgument argNum2 = calcArgsList[index + 1]; //do * or / operations int subtotal = PerformCalculation(multDivOp, argNum1.GetNumber(), argNum2.GetNumber()); //Put result of * or / operations back in with ALL args list wasReplaced = ReplaceWithSubtotal(subtotal, index); } printCalcArgsList("After*/"); // What remains in the sorted list are the addition and subtraction operations int calcArgsListSize = calcArgsList.Count() + 1; for (int i = 1; i <= (calcArgsListSize / 3); i++) { int num1 = calcArgsList.ElementAt(0).GetNumber(); string oper = calcArgsList.ElementAt(1).GetOperator(); int num2 = calcArgsList.ElementAt(2).GetNumber(); int subtotal = PerformCalculation(oper, num1, num2); wasReplaced = ReplaceWithSubtotal(subtotal, 1); } // For debug purposes only printCalcArgsList("After+-"); int total = calcArgsList.ElementAt(0).GetNumber(); return(total); }
/// <summary> /// Constructor that creates class objects of the type CalculatorArgument and saves /// them in a list for later access. /// </summary> public Calculator() { int position = 0; foreach (KeyValuePair <int, string> element in calcArgsStr) { CalculatorArgument calcArg = new CalculatorArgument(position, element.Value); if (calcArg.IsMultDivOp()) { divMulOps.Add(position, element.Value); } calcArgsList.Insert(position, calcArg); position += 1; } }