Last active
August 29, 2015 14:22
-
-
Save trcio/e26e49fae0d8faddbc66 to your computer and use it in GitHub Desktop.
Finding the least amount of bills/coins for any monetary value (using common bills/coins, no $2 bill, 50 cent coin, etc)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChangeCalculator | |
{ | |
public static Dictionary<decimal, decimal> GetUsdChange(decimal dollars) | |
{ | |
return GetChange(dollars, new[] {100, 50, 20, 10, 5, 1, .25M, .10M, .05M, .01M}); | |
} | |
public static Dictionary<decimal, decimal> GetChange(decimal amount, IEnumerable<decimal> denominations) | |
{ | |
denominations = denominations.OrderByDescending(i => i); | |
var dictionary = new Dictionary<decimal, decimal>(); | |
foreach (var denom in denominations) | |
{ | |
var quantity = decimal.Truncate(amount / denom); | |
if (quantity > 0) | |
dictionary.Add(denom, quantity); | |
amount = decimal.Subtract(amount, decimal.Multiply(quantity, denom)); | |
} | |
return dictionary; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment