For the fun of it, I would like to see someone use and abuse LINQ to solve this money problem. I really have no idea how you would do it - I suppose Populating some set and then selecting off of it.
If given a total number of coins and give the total amount of all coins added together: Show every possible combination of coins. Coins are Quarters(.25), Dimes(.10) Nickels(.05) and Pennies(.01)
Include the option so that there can be zero of a type of coin or there must be at least 1 of each.
Sample Problem: If I have 19 coins and the coins add up to $1.56 and there must be at least 1 of every type of coin.
The answer would be:
1 Quarters, 9 Dimes, 8 Nickels, 1 Pennies
2 Quarters, 5 Dimes, 11 Nickels, 1 Pennies
2 Quarters, 9 Dimes, 2 Nickels, 6 Pennies
3 Quarters, 1 Dimes, 14 Nickels, 1 Pennies
3 Quarters, 5 Dimes, 5 Nickels, 6 Pennies
4 Quarters, 1 Dimes, 8 Nickels, 6 Pennies
5 Quarters, 1 Dimes, 2 Nickels, 11 Pennies
And if we allowed zero for a coint we allowed get an additional 0 Quarters, 13 Dimes, 5 Nickels, 1 Pennies
Here is some sample C# code using a brute force method to solve the problem. Don't bother improving the sample, let's just see a solution using Linq. //Try not to use any regualar c# looping code if possible.
private void SolveCoinProblem(int totalNumberOfCoins, double totalAmount, int minimumNumberOfEachCoin)
{
int foundCount = 0;
long numberOfTries = 0;
Console.WriteLine(String.Format("Solving Coin Problem:TotalNumberOfCoins={0}TotalAmount={1}MinimumNumberOfEachCoin{2}", totalNumberOfCoins, totalAmount, minimumNumberOfEachCoin));
for (int totalQuarters = minimumNumberOfEachCoin; totalQuarters < totalNumberOfCoins; totalQuarters++)
{
for (int totalDimes = minimumNumberOfEachCoin; totalDimes < totalNumberOfCoins; totalDimes++)
{
for (int totalNickels = minimumNumberOfEachCoin; totalNickels < totalNumberOfCoins; totalNickels++)
{
for (int totalPennies = minimumNumberOfEachCoin; totalPennies < totalNumberOfCoins; totalPennies++)
{
numberOfTries++;
if (totalQuarters + totalDimes + totalNickels + totalPennies == totalNumberOfCoins)
{
if (Math.Round((totalQuarters * .25) + (totalDimes * .10) + (totalNickels * .05) + (totalPennies * .01),2) == totalAmount)
{
Console.WriteLine(String.Format("{0} Quarters, {1} Dimes, {2} Nickels, {3} Pennies", totalQuarters, totalDimes, totalNickels, totalPennies));
foundCount++;
}
}
}
}
}
}
Console.WriteLine(String.Format("{0} Combinations Found. We tried {1} combinations.", foundCount, numberOfTries));
}