Created
January 7, 2022 01:21
-
-
Save kolosovpetro/d45874de581fbe996cde62e6d162e767 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| namespace CoinChangeProblem | |
| { | |
| public static class DynamicChangeHelper | |
| { | |
| public static int MinimalChangeForCoin(int coin, IEnumerable<int> coins) | |
| { | |
| if (coin <= 0) | |
| { | |
| throw new IndexOutOfRangeException("Coin cannot be lesser or equal to zero."); | |
| } | |
| var coinsAsArray = coins.ToArray(); | |
| if (coinsAsArray.Length == 0) | |
| { | |
| throw new IndexOutOfRangeException("Coins array cannot be empty."); | |
| } | |
| var coinsContainOne = coinsAsArray.Any(x => x == 1); | |
| if (!coinsContainOne) | |
| { | |
| throw new IndexOutOfRangeException("Coins array must contain coin 1."); | |
| } | |
| Array.Sort(coinsAsArray); | |
| Array.Reverse(coinsAsArray); | |
| foreach (var item in coinsAsArray) | |
| { | |
| if (item > coin) | |
| { | |
| continue; | |
| } | |
| return item; | |
| } | |
| return 0; | |
| } | |
| public static int[] MakeChange(int coin, IEnumerable<int> coins) | |
| { | |
| var changeArr = coins.ToArray(); | |
| var list = new List<int>(); | |
| var currentCoin = coin; | |
| while (currentCoin > 0) | |
| { | |
| var currentChange = MinimalChangeForCoin(currentCoin, changeArr); | |
| list.Add(currentChange); | |
| currentCoin -= currentChange; | |
| } | |
| var result = list.ToArray(); | |
| return result; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment