Below is link to one solution for similar problem. What I want to add to this solution is that combinations should be limited only to those items which satisfy total sum condition.
https://stackoverflow.com/a/10629938/4347577
Thanks in advance
Below is link to one solution for similar problem. What I want to add to this solution is that combinations should be limited only to those items which satisfy total sum condition.
https://stackoverflow.com/a/10629938/4347577
Thanks in advance
The simplest solution is to add a where
clause that filters for the results that you want. For example:
public static IEnumerable<IEnumerable<int>> GetPermutationsWithSum(
IEnumerable<int> list, int length, int sum)
{
return GetPermutationsWithRept(list, length).Where(lst => lst.Sum() == sum);
}
Here is the definition for GetPermutationsWithRept (from the answer you linked to in your question)
public static IEnumerable<IEnumerable<T>> GetPermutationsWithRept<T>(
IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutationsWithRept(list, length - 1)
.SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
}