Advertisement
svetlyoek

Untitled

Jun 26th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 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. var targetSum = 2031154123;
  11.  
  12. var selectedCoins = ChooseCoins(availableCoins, targetSum);
  13.  
  14. Console.WriteLine($"Number of coins to take: {selectedCoins.Values.Sum()}");
  15. foreach (var selectedCoin in selectedCoins)
  16. {
  17. Console.WriteLine($"{selectedCoin.Value} coin(s) with value {selectedCoin.Key}");
  18. }
  19. }
  20.  
  21. public static Dictionary<int, int> ChooseCoins(IList<int> coins, int targetSum)
  22. {
  23. var choosenCoins = new Dictionary<int, int>();
  24. int coinIndex = 0;
  25. int currentSum = 0;
  26.  
  27. var sortedCoins = coins.OrderByDescending(c => c).ToList();
  28.  
  29. while (currentSum < targetSum && coinIndex < sortedCoins.Count)
  30. {
  31. var currrentCoinValue = sortedCoins[coinIndex];
  32. var remainingSum = targetSum - currentSum;
  33. var numberOfCoinsToTake = remainingSum / currrentCoinValue;
  34.  
  35. if (numberOfCoinsToTake > 0)
  36. {
  37. if(!choosenCoins.ContainsKey(currrentCoinValue))
  38. {
  39. choosenCoins.Add(currrentCoinValue, 0);
  40. }
  41.  
  42. choosenCoins[currrentCoinValue]=numberOfCoinsToTake;
  43.  
  44. }
  45.  
  46. coinIndex++;
  47. }
  48.  
  49. return choosenCoins;
  50.  
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement