Advertisement
astanchev

SumOfCoins

Jun 26th, 2019
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class SumOfCoins
  6. {
  7. public static void Main(string[] args)
  8. {
  9. var availableCoins = new[] { 1, 2, 5, 10, 20, 50 };
  10. var targetSum = 923;
  11.  
  12. try
  13. {
  14. var selectedCoins = ChooseCoins(availableCoins, targetSum);
  15.  
  16. Console.WriteLine($"Number of coins to take: {selectedCoins.Values.Sum()}");
  17. foreach (var selectedCoin in selectedCoins)
  18. {
  19. Console.WriteLine($"{selectedCoin.Value} coin(s) with value {selectedCoin.Key}");
  20. }
  21. }
  22. catch (Exception e)
  23. {
  24. Console.WriteLine(e.Message);
  25. }
  26.  
  27. }
  28.  
  29. public static Dictionary<int, int> ChooseCoins(IList<int> coins, int targetSum)
  30. {
  31. var sortedCoins = coins
  32. .OrderByDescending(c => c)
  33. .ToList();
  34.  
  35. var chosenCoins = new Dictionary<int, int>();
  36. int currentSum = 0;
  37. int coinIndex = 0;
  38.  
  39. while (currentSum != targetSum && coinIndex < sortedCoins.Count)
  40. {
  41. int currentCoinValue = sortedCoins[coinIndex];
  42. int remainingSum = targetSum - currentSum;
  43. int numberOfCoinToTake = remainingSum / currentCoinValue;
  44.  
  45. if (numberOfCoinToTake > 0)
  46. {
  47. chosenCoins[currentCoinValue] = numberOfCoinToTake;
  48.  
  49. currentSum += currentCoinValue * numberOfCoinToTake;
  50. }
  51.  
  52. coinIndex++;
  53.  
  54. }
  55.  
  56. if (currentSum == targetSum)
  57. {
  58. return chosenCoins;
  59. }
  60. else
  61. {
  62. throw new InvalidOperationException();
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement