The Cash Machine

You have an ATM with a fixed amount of bills (10’s,5’s & 1’s) and a balance of 1000 dollars.
Give me code that can return those bills without exceeding the bills the machine has available.

My answer:

protected void btnGetCash_Click(object sender, EventArgs e)
{
string msg = string.Empty;
Response.Write(Withdraw(System.Convert.ToDecimal(txtAmount1.Text), ref msg).ToString());
if (msg != null)
{
Response.Write(msg);
}
}

private decimal Withdraw(decimal amount, ref string message)
{
decimal currentAmount = 0;
int cashAvailable = 1000;

StringBuilder CashUsed = new StringBuilder(”
“);

if (amount > cashAvailable)
{
message = “Not enough funds available”;
}

for (int i = 1; i < cashAvailable; i++)
{

if (currentAmount == amount)
{
message += CashUsed.ToString();
return currentAmount;
}

if (currentAmount < amount && BillsAreAvailable(10) && ((amount – currentAmount) / 10) % 10 == 0 || currentAmount +10 < amount && BillsAreAvailable(10)  && ((amount – currentAmount) / 10) / 10 > 0)
{
currentAmount += 10;
CashUsed.Append(“$10”);
}
else if (currentAmount < amount && BillsAreAvailable(5) && ((amount – currentAmount) / 5) % 5 == 0 || currentAmount +10 < amount && BillsAreAvailable(5) && ((amount – currentAmount) / 5) / 5 > 0)
{
currentAmount += 5;
CashUsed.Append(“$5”);
}
else if (currentAmount < amount && ((amount – currentAmount) / 1) % 1 == 0)
{
currentAmount += 1;
CashUsed.Append(“$1”);
}
}

return currentAmount;
}

private bool BillsAreAvailable(Int32 _billToCheckFor){

if(BigDataContext.IncrementAvailable( _billToCheckFor)){

BigDataContext.RemoveAmount(_billToCheckFor);

return true;

}

return false;

}

}

Advertisements