I have a list of numbers and I want to know which combination of the numbers in the list has the closest sum to a specific number(Target).( if there are many combinations, finding one is enough)
I searched a lot and know that there are lots of solutions here to find the combinations that their sum is equal to specific number, but there were no solution to find the greatest close to that number.
I also wrote a piece of code that loops from zero to "Target" to find the biggest sum, but as this process is so time consuming as it must be calculated for 100,000 lists, i wonder if there is more efficient way using preferably linq.
var List1 = new int[] { 5, 10, 15, 20, 25, 30, 35, 40, 45 };
var target = 40;
int MaxViewers = Convert.ToInt32(txtNoRecordsToAdd.Text);
for (int UserNo = 1; UserNo <= MaxViewers; UserNo++)
{
for (int No = 1; No <= target; No++)
{
var matches = from subset in MyExtensions.SubSetsOf(List1)
where subset.Sum() == target
select subset;
}
}
public static class MyExtensions
{
public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(this IEnumerable<T> source)
{
if (!source.Any())
return Enumerable.Repeat(Enumerable.Empty<T>(), 1);
// Grab the first element off of the list
var element = source.Take(1);
// Recurse, to get all subsets of the source, ignoring the first item
var haveNots = SubSetsOf(source.Skip(1));
// Get all those subsets and add the element we removed to them
var haves = haveNots.Select(set => element.Concat(set));
// Finally combine the subsets that didn't include the first item, with those that did.
return haves.Concat(haveNots);
}
}