Calculate change in coins various languages
Given the prompt of some amount less than the smallest bill available calculate the remaining coins to distribute. This is also ok for bill amounts as well if you wanted to reuse it. This is also how you would do pagination as well as it is the first pass of this problem i.e. you will only have 1
divisor, but it's the same idea
C#
public static Dictionary<string, int> GetChange(int totalChange, int[]? coinValues)
{
if (totalChange > 99)
{
throw new ArgumentException("The total change must be less than 100.");
}
var results = new Dictionary<string, int>();
foreach (var coinValue in (coinValues ?? []).Distinct().OrderByDescending(x => x))
{
var (q,r) = Math.DivRem(totalChange, coinValue);
if (q > 0)
{
results.Add(coinValue.ToString(), q);
}
if (r <= 0)
{
break;
}
totalChange -= q * coinValue;
}
return results;
}
var coins = GetChange(93, [25, 10, 5, 1]);
foreach (var coinValue in coins)
{
Console.WriteLine($"{int.Parse(coinValue.Key):00}: {coinValue.Value}");
}
Results
25: 3
10: 1
05: 1
01: 3
Python
def get_change(total_change: int, coin_values: list[int]) -> dict:
results = {}
safe_list = list(set([] if coin_values is None else coin_values))
safe_list.sort(reverse=True)
for coin_value in safe_list:
q, r = divmod(total_change, coin_value)
if q > 0:
results[coin_value] = q
if r <= 0:
break
total_change -= q * coin_value
return results
coins = get_change(93, [25, 10, 5, 1])
for (coin_value, coins) in coins.items():
print(f'{str(coin_value).zfill(2)}: {coins}')
25: 3
10: 1
05: 1
01: 3