Home > Mobile >  Simple ATM Algorithm
Simple ATM Algorithm

Time:05-19

I have a simple ATM algorithm that, given an amount to take, should deliver the minimum amount of 100 bills, 50 bills, and 20 bills.

var amount = 280;
var availableBiils = new[] { 100, 50, 20 };
var usedNumberOfBills = new[] { 0, 0, 0 };

for (var i = 0; i < availableBiils.Count(); i  )
{
    var bill = availableBiils[i];
    while (amount >= bill)
    {
        amount = amount - bill;

        usedNumberOfBills[i]  = 1;
    }
}

for (var i = 0; i < usedNumberOfBills.Length; i  )
{
    Console.WriteLine($"{availableBiils[i]}    {usedNumberOfBills[i]}");
}

My approach does not work for some cases, for example 280, 260, 240, and so on.

CodePudding user response:

Your unique problem is when you have 60 or 80. In these cases you take 50 and remain 10 or 30 that you can't solve. Simply check this cases.

var amount = 280;
var availableBiils = new[] { 100, 50, 20 };
var usedNumberOfBills = new[] { 0, 0, 0 };

for (var i = 0; i < availableBiils.Count(); i  )
{
    var bill = availableBiils[i];
    while (amount >= bill)
    {
        if (amount == 60)
        {
            amount = 0;
            usedNumberOfBills[2]  = 3;
        }
        else if (amount == 80)
        {
            amount = 0;
            usedNumberOfBills[2]  = 4;
        }
        else
        {
            amount = amount - bill;
            usedNumberOfBills[i]  = 1;
        }
    }
}

for (var i = 0; i < usedNumberOfBills.Length; i  )
{
    Console.WriteLine($"{availableBiils[i]}    {usedNumberOfBills[i]}");
}

If your available bills are well known, you may also do this:

var amount = 280;
var availableBiils = new[] { 100, 50, 20 };
var usedNumberOfBills = new[] { 0, 0, 0 };
            
usedNumberOfBills[0] = Math.DivRem(amount, 100, out int pending);

if (pending != 60 && pending != 80)
{
    usedNumberOfBills[1] = Math.DivRem(pending, 50, out amount);
    usedNumberOfBills[2] = amount / 20;
}
else
{
    usedNumberOfBills[2] = pending / 20;
}

for (var i = 0; i < usedNumberOfBills.Length; i  )
{
    Console.WriteLine($"{availableBiils[i]}    {usedNumberOfBills[i]}");
}

CodePudding user response:

Your algorithm will work for every amount only, if for each bill (excluding lowest) you have at least one bill, that divided gives whole number. For 50 only lower bill is 20, but 50/20=2.5, so it isn't whole number.

Simplest solution is to add 10 bill.

  •  Tags:  
  • c#
  • Related