【发布时间】:2015-08-13 19:54:52
【问题描述】:
我有一个数字列表,我想知道列表中哪个数字组合与特定数字(目标)的总和最接近。(如果有很多组合,找到一个就足够了)
我搜索了很多,知道这里有很多解决方案可以找到它们的总和等于特定数字的组合,但是没有找到与该数字接近的最大的解决方案。
我还写了一段代码,从零循环到“目标”以找到最大的和,但由于这个过程非常耗时,必须针对 100,000 个列表进行计算,我想知道是否有更有效的方法使用最好是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);
}
}
【问题讨论】:
-
您是否考虑过将
MaxBy与Sum结合使用? -
@testWell,感谢您的评论,请您提供示例源代码
-
@Ramil89,感谢您的链接。不幸的是,这个算法对于 100,000 个列表非常耗时,我正在寻找更有效的解决方案。
-
当您说
find the greatest close to that number时,您的意思是要返回在目标的某个范围 内但实际上不是目标的多个匹配项?如果是这样,您可以将您的where语句更改为更像where subset.Sum() > target - 5 && subset.Sum() < target,它将返回目标5 以内的所有子集。这将为您提供所有密切的可能性。
标签: c# performance linq