Tuesday, April 9, 2013

Write a C# method to implement a change dispenser.

Question :

Write a C# method to implement a change dispenser. The change dispenser takes in a number of higher denomination and returns the smallest number of lower denominations to dispense. The method should return the denominations and the counts of those denominations.

Example: if the dispenser has $1 and $5 denominations only and the method is called with $19, then it should return 3 * $5 and 4 * $1 instead of 19 * $1 denominations as it means fewer notes. So it should return both the above denominations and their counts to the caller.

For the implementation, assume you have $1, $2, $5 and $10 denominations only, and find the least number of denominations to break a given higher denomination. Assume only whole number denominations. No need to specify '$' in the method as it is used only for representation.


Solution:
namespace Excercises
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter the money you need the change for :");
string value = Console.ReadLine();

int TotalMoney = Int32.Parse(value);
if (TotalMoney <= 0) { Console.WriteLine("Invalid number entered. Please try again"); } if (TotalMoney > 0)
{
ChangeDispenser(TotalMoney);
}


Console.ReadKey();
}

public static void ChangeDispenser(int n)
{
//avaialble denominations $10, $5, $2, $1
int numOfTens = 0;
int numOfFives = 0;
int numOfTwos = 0;
int numOfOnes = 0;

if (n >= 10)
{
numOfTens = n / 10;
n= n%10;
}
if (n >= 5)
{
numOfFives = n / 5;
n = n % 5;
}
if (n >= 2)
{
numOfTwos = n / 2;
n = n % 2;
}
numOfOnes = n;

Console.WriteLine("Number of 10s: {0}, Number of 5s : {1}, Number of 2s : {2}, Numer of 1s : {3}", numOfTens, numOfFives, numOfTwos, numOfOnes);

}
}
}

No comments: