Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // test
- for (int i = 1; i <= 200; i++)
- {
- Dictionary<int, int> change = MakeChange(new List<int> { 1, 5, 10, 25, 50 }, i);
- Debug.WriteLine($"sum {i}");
- int sum = 0;
- foreach (KeyValuePair<int, int> coins in change)
- {
- sum += coins.Key * coins.Value;
- Debug.WriteLine($" coin {coins.Key} count {coins.Value} ");
- }
- if (i != sum)
- {
- Debug.WriteLine("problem");
- }
- }
- // end test
- private static Dictionary<int, int> MakeChange(List<int> coins, int sum)
- {
- if(sum < 0 || coins.Count == 0)
- {
- throw new ArgumentOutOfRangeException();
- }
- Dictionary<int, int> change = new Dictionary<int, int>();
- foreach (int coin in coins.Distinct().Where(x => x > 0).OrderByDescending(x => x))
- {
- int j = sum / coin; //integer math rounds down
- if (j > 0)
- {
- change.Add(coin, j);
- }
- sum -= j * coin;
- if (sum == 0)
- return change;
- }
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement