I have written the following code that returns all possible ways to represent a certain amount of money using coins in a currency with a certain set of coin values:
IEnumerable<IEnumerable<int>> getCoins(int price)
{
int[] coinValues = new int[] { 1, 2, 5, 10, 20, 50, 100, 200 }; // Coin values
if (coinValues.Contains(price)) yield return new int[] { price }; // If the price can be represented be a single coin
// For every coin that is smaller than the price, take it away, call the function recursively and concatenate it later
foreach (int coin in coinValues.Where(x => x < price))
foreach (IEnumerable<int> match in getCoins(price - coin))
yield return match.Concat(new int[] { coin });
}
This works fine, but for instance for price = 3 it treats {1c, 2c} and {2c, 1c} as two different representations. That issue can be resolved by storing all found values in a List and then remove duplicates when they are generated, but that way the generator nature of the code is sacrificed. Can the code be modified to not include duplicates while still being a generator using yield return?