Skip to content

Instantly share code, notes, and snippets.

@trcio
Last active August 29, 2015 14:22
Show Gist options
  • Save trcio/e26e49fae0d8faddbc66 to your computer and use it in GitHub Desktop.
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)
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