Guest User

Untitled

a guest
Nov 18th, 2019
179
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. 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 coinsDictionary = new Dictionary<int, int>();
  24. int sum = 0;
  25. coins = coins.OrderByDescending(x => x).ToList();
  26.  
  27. for (int i = 0; i < coins.Count; i++)
  28. {
  29. while (sum + coins[i] <= targetSum)
  30. {
  31. sum += coins[i];
  32. if (!coinsDictionary.ContainsKey(coins[i]))
  33. {
  34. coinsDictionary.Add(coins[i], 0);
  35. }
  36. coinsDictionary[coins[i]]++;
  37. }
  38. if (sum == targetSum) break;
  39. }
  40.  
  41. if (sum != targetSum)
  42. {
  43. Console.WriteLine("Error");
  44. Environment.Exit(0);
  45. }
  46.  
  47. return coinsDictionary;
  48. }
  49. }
RAW Paste Data