查找与目标号码

时间:2015-09-21 19:10:00

标签: c# linq list combinations

我有一个有趣的问题,我试图解决。我对Linq的了解实在是非常浅薄,而且我很确定这是使用基于Linq的解决方案最优雅地解决的问题,但到目前为止,我已经尝试了一些基本知识的东西。不太成功。

这里是瘦的:我有一个十进制列表列表,我想从列表中找到一个组合,只使用每个列表中的一个元素来累加目标小数。澄清:

List<List<decimal>> parentList; // this is the main list I'm drawing from
List<decimal> childList { 1 , 2 , 3 , 4 , 5 }; // each list inside of the main list would look something like this

因此,如果我的parentList包含五个childLists,我需要找到一个组合,每个列表只使用一个项目一次。这并不意味着我不能两次使用相同的值,如果parentList [0]和parentList [1]都包含3而I&#39; m加到6,{3,3}将是有效解决方案但是,如果parentList [0]为{1,2,3}且parentList [1]为{4},则添加到6的唯一有效解决方案是{2,4},因为第二个列表不是{4}包含3。

我希望这一切都有道理,而且我不会问太多。我不介意只是朝着解决方向的方向,朝着正确的方向而不是整个答案。谢谢!

3 个答案:

答案 0 :(得分:0)

听起来像使用递归而不是Linq解决的问题。这是一个例子:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<decimal>> listOfLists = new List<List<decimal>>()
            {
                new List<decimal>() { 1, 2, 3 },
                new List<decimal>() { 3, 4, 5 },
                new List<decimal>() { 5, 6, 7 },
            };

            PrintAllCombinationsForTargetValue(listOfLists, 12);
        }

        private static void PrintAllCombinationsForTargetValue(List<List<decimal>> listOfLists, decimal targetValue)
        {
            Stack<decimal> currentCombination = new Stack<decimal>();
            FindNextElement(listOfLists, targetValue, 0, 0, currentCombination);
        }

        private static void FindNextElement(List<List<decimal>> listOfLists, decimal targetValue, int listIndex, decimal trackingValue, Stack<decimal> currentCombination)
        {
            List<decimal> currentList = listOfLists[listIndex];
            foreach (decimal currentValue in currentList)
            {
                decimal currentTrackingValue = trackingValue + currentValue;
                currentCombination.Push(currentValue);

                if (currentTrackingValue < targetValue && listIndex < listOfLists.Count - 1)
                {
                    // There is still la chance that we can get what we want. Let's go to the next list.
                    FindNextElement(listOfLists, targetValue, listIndex + 1, currentTrackingValue, currentCombination);
                }
                else if (currentTrackingValue == targetValue && listIndex == listOfLists.Count - 1)
                {
                    // Found a valid combination!
                    currentCombination.Reverse().ToList().ForEach(element => Console.Write(element + " "));
                    Console.WriteLine();
                }

                currentCombination.Pop();
            }
        }
    }
}

答案 1 :(得分:0)

您可以通过递归实现此目的。这将找到一个总结到目标的组合,使用每个列表中的一个值,如果不存在则为null。

public static List<decimal> CombinationSumMatches(
    this IEnumerable<IEnumerable<decimal>> lists, 
    decimal target)
{
    if (lists.Any())
    {
        var firstList = lists.First();
        if (lists.Skip(1).Any())
        {
            foreach (var num in firstList)
            {
                var newTarget = target - num;
                var subCombination = lists.Skip(1).CombinationSumMatches(newTarget);
                if (subCombination != null)
                {
                    subCombination.Insert(0, num);
                    return subCombination;
                }
            }
        }
        else
        {
            if (firstList.Contains(target))
            {
                return new List<decimal> { target };
            }
        }
    }

    return null;
}

这将首先检查是否有任何列表。如果有,那么它会查看第一个并查看是否还有更多。如果还有更多,它会遍历第一个列表的每个数字,并从目标中减去该值,并对其余列表进行递归调用。如果存在非空答案,则插入数字并返回。现在,如果只有一个列表,那么它只检查目标列表,如果找到它则返回一个包含该目标值的列表。如果没有列表,或者只有一个没有目标,或者没有任何匹配子组合,那么它只会返回null

答案 2 :(得分:0)

正如其他人已经说过的那样,LINQ不适合这样的任务。从维护和性能的角度来看,这样复杂的LINQ并不好。

但是我不能停下来,直到我内心的怪人开心!你问过它......

private static IEnumerable<IEnumerable<decimal>> FindCombinations(IEnumerable<IEnumerable<decimal>> listOfLists, decimal target)
{
    return listOfLists.Aggregate(
        Enumerable.Repeat(Enumerable.Empty<decimal>(), 1),
        (acc, seq) =>
            from accseq in acc
            from item in seq
            select accseq.Concat(new[] {item}))
        .Where(x => x.Sum(y => y) == target);
}

这是控制台测试应用程序:

private static void Main(string[] args)
{
    var target = 12;
    var listOfLists = new List<List<decimal>>()
    {
        new List<decimal> { 1, 2, 3 },
        new List<decimal> { 3, 4, 5 },
        new List<decimal> { 5, 6, 7 },
    };

    foreach (var combination in FindCombinations(listOfLists, target))
    {
        Console.WriteLine("{0} = {1}", string.Join(" + ", combination.Select(y => y.ToString(CultureInfo.InvariantCulture))), target);
    }
    Console.ReadKey();
}
相关问题