【问题标题】:Matching integers in a list匹配列表中的整数
【发布时间】:2013-09-20 13:26:13
【问题描述】:

鉴于我有一个这样的整数列表:

List<int> items = new List<int> {200, 100, 50, 20, 10, 5, 2, 1};

如果我有一个数字,比如 13,我将如何使用 LINQ(或任何其他方式)从列表中找到加起来为 13 的数字。该列表始​​终按降序排列。

例如:13 = 10 + 2+ 1,所以 linq 操作会返回一个包含 10,2 和 1 的整数列表。

如果我们无法找到完全匹配的情况,如 24 的情况,则可以生成异常。

努力:

  [Test]
        public void Should_find_subset()
        {
            var items = new List<int>() {200, 100, 50, 20, 10, 5, 2, 1};

            var find = 13;
            var result = new List<int>();
            var subset = new List<int>();
            bool found = false;

            foreach (var item in items)
            {
                if (item == find)
                {
                    result.Add(item);
                    found = true;
                }

                if (item < find)
                {
                    subset.Add(item);
                    found = subset.Sum() == find;
                }

                if (found)
                    break;
            }
        }

谢谢,

-迈克

【问题讨论】:

  • 到目前为止有什么努力吗?
  • 你尝试过什么了吗?
  • 你能告诉我们一些你尝试过的东西吗?
  • 如果这是作业,你应该这样标记它。
  • 有点类似于几天前提出的这个问题:stackoverflow.com/questions/18801466/…。是否有一些新的在线材料或什么的? ;)

标签: c# linq


【解决方案1】:

如果我听到组合我建议这个项目:Permutations, Combinations, and Variations

这是工作代码:

List<int> items = new List<int> { 200, 100, 50, 20, 10, 5, 2, 1 };
var allMatchingCombos = new List<IList<int>>();
for (int i = 1; i < items.Count; i++)
{
    IEnumerable<IList<int>> matchingCombos = new Combinations<int>(items, i, GenerateOption.WithoutRepetition)
        .Where(c => c.Sum() == 13);
     allMatchingCombos.AddRange(matchingCombos);
}

foreach(var combo in allMatchingCombos)
   Console.WriteLine(string.Join(",", combo));

输出:10,2,1

编辑:由于您已明确要求使用 LINQ,因此这是一个完整的 LINQified 方法:

List<IList<int>> allMatchingCombos = Enumerable.Range(1, items.Count)
    .SelectMany(i => new Combinations<int>(items, i, GenerateOption.WithoutRepetition)
                    .Where(c => c.Sum() == 13)
                    .ToList())
    .ToList();

【讨论】:

  • +1 哈,我怎么能忘记呢?请注意,您还可以在 NuGet 中找到此库,名为 Combinatorics Library for .NET
【解决方案2】:

使用Aggregate的简单而低效的方法:

List<int> items = new List<int> {200, 100, 50, 20, 10, 5, 2, 1};
var target = 373;

var result = items.Aggregate(new List<int>(), (acc, curr) => 
{
    if (acc.Sum() + curr <= target)
        acc.Add(curr);
    return acc;     
});

if(result.Sum() != target)
    throw new Exception(); // whatever

结果:

我应该注意,这种简单的方法并不适用于所有情况。例如。 List 是 68,50,20,target 是 70。这会导致错误,而不是 50, 20。

另一种处理此类情况的低效方法:

List<int> items = new List<int> {68, 50, 20};
var target = 70;

var result = new List<int>();
while(result.Sum() != target && items.Any())
{
    result = new List<int>();
    foreach (var item in items)
        if (result.Sum() + item <= target)
            result.Add(item);
    if(result.Sum() != target)
        items.Remove(result.Last());
}

if(result.Sum() != target)
    throw new Exception(); // whatever, no solution found

结果:

使用大型输入列表可能会非常慢。

【讨论】:

  • +1 为 LinqPad,我会再为throw new Exception(); // whatever 加 1,因为它让我想起了一个停止提供 sh*t 的程序员。 :)
  • 如果项目不能重复使用则更正
猜你喜欢
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 2019-05-28
相关资源
最近更新 更多