Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. // test
  2. for (int i = 1; i <= 200; i++)
  3. {
  4. Dictionary<int, int> change = MakeChange(new List<int> { 1, 5, 10, 25, 50 }, i);
  5. Debug.WriteLine($"sum {i}");
  6. int sum = 0;
  7. foreach (KeyValuePair<int, int> coins in change)
  8. {
  9. sum += coins.Key * coins.Value;
  10. Debug.WriteLine($" coin {coins.Key} count {coins.Value} ");
  11. }
  12. if (i != sum)
  13. {
  14. Debug.WriteLine("problem");
  15. }
  16. }
  17.  
  18. // end test
  19.  
  20. private static Dictionary<int, int> MakeChange(List<int> coins, int sum)
  21. {
  22. if(sum < 0 || coins.Count == 0)
  23. {
  24. throw new ArgumentOutOfRangeException();
  25. }
  26. Dictionary<int, int> change = new Dictionary<int, int>();
  27. foreach (int coin in coins.Distinct().Where(x => x > 0).OrderByDescending(x => x))
  28. {
  29. int j = sum / coin; //integer math rounds down
  30. if (j > 0)
  31. {
  32. change.Add(coin, j);
  33. }
  34. sum -= j * coin;
  35. if (sum == 0)
  36. return change;
  37. }
  38. return null;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement