I have a list of products that have an ID and a Quantity, and I need to find a list of combinations of products that will fill a certain quantity.
E.g.
ProductID | Quantity
1 | 5
2 | 5
3 | 8
4 | 15
If I require a quantity of 15 then I want to get a list with the following combinations:
Products: {1, 2, 3}, {1, 3, 2}, {1, 2, 4}, {1, 3, 4}, {1, 4}
{2, 1, 3}, {2, 1, 4}, {2, 3, 1}, {2, 3, 4}, {2, 4}
{3, 1, 2}, {3, 1, 4}, {3, 2, 1}, {3, 2, 4}, {3, 4}
{4}
It's almost a permutation, but it's filtered out entries that sum up to more than what is required. I need to stop taking further items, if at any point, the current total sum of values goes beyond 15. Doing this way, if I had all permutations then I would have 24 results, but I only have 16.
E.g. if I take product 4 then I don't need to combine it with anything to make 15. Similarly, if I take product 1 then take product 4, I don't need to pick up anymore item since the sum is already beyond 15 (5 + 15 = 20).
I was able to get the code working by getting all Permutations (e.g. here) and then filtering that down to the ones I care about, however once you start getting a large number of products (e.g. 30) then you end up with 4.3 Billion combinations which causes out of memory exceptions.
How can I create only the required permutations in C#?