public void CalculateChange() { // combine cash in hand and cash received CashRegister newCashInHand = CashRegister.Combine(_cashInHands, _cashReceived); _cashChange = new CashRegister(CashDenomination.ALL_DONOMINATIONS); int change = _cashReceived.Amount - _amountDue; // deduct from max to min denominations as needed newCashInHand.Sort(ListSortDirection.Descending); foreach (CashSet fromSet in newCashInHand.CashSets) { if (change > fromSet.Denomination.Amount) { int qty = (int)(change / fromSet.Denomination.Amount); if (qty > fromSet.Quantity) { qty = fromSet.Quantity; } fromSet.Quantity = fromSet.Quantity - qty; CashSet toSet = _cashChange.CashSets.First(s => s.Denomination.Amount == fromSet.Denomination.Amount); toSet.Quantity = toSet.Quantity + qty; change -= fromSet.Denomination.Amount * qty; } if (change <= 0) { break; } } // if still remained, deduct from the min to max denomination to make it zero if (change > 0) { newCashInHand.Sort(ListSortDirection.Ascending); foreach (CashSet fromSet in newCashInHand.CashSets) { int qty = (int)(change / fromSet.Denomination.Amount) + 1; if (qty > fromSet.Quantity) { qty = fromSet.Quantity; } fromSet.Quantity = fromSet.Quantity - qty; CashSet toSet = _cashChange.CashSets.First(s => s.Denomination.Amount == fromSet.Denomination.Amount); toSet.Quantity = toSet.Quantity + qty; change -= fromSet.Denomination.Amount * qty; if (change <= 0) { break; } } } }
public static CashRegister Combine(CashRegister register1, CashRegister register2) { CashRegister newCashRegister = new CashRegister(CashDenomination.ALL_DONOMINATIONS); foreach (CashDenomination d in CashDenomination.ALL_DONOMINATIONS) { CashSet set = newCashRegister.CashSets.FirstOrDefault(s => s.Denomination.Amount == d.Amount); CashSet s1 = register1.CashSets.FirstOrDefault(s => s.Denomination.Amount == d.Amount); if (s1 != null) { set.Quantity = set.Quantity + s1.Quantity; } CashSet s2 = register2.CashSets.FirstOrDefault(s => s.Denomination.Amount == d.Amount); if (s2 != null) { set.Quantity = set.Quantity + s2.Quantity; } } return(newCashRegister); }