找到两个数组元素的所有可能的总和

时间:2015-02-07 17:13:33

标签: c#

我有两个数组,我试图获得每个元素的所有可能的总和与两个数组的其他元素和每个元素的索引

int[] width = new int[2] {10,20 };
int[] height = new int[2] {30,40 };

结果应该是这样的(值/索引)

10 width0

10 + 20 width0 + width1

10 + 30 width0 + height0

10 + 40 width0 + height1

10 + 20 + 30 width0 + width1 + height0

10 + 20 + 40 width0 + width1 + height1

10 + 20 + 30 + 40 width0 + width1 + height0 + height1

对于两个数组中的每个元素

我尝试使用排列,但我得到了其他输出

2 个答案:

答案 0 :(得分:3)

从一个阵列获取所有组合比两个阵列更容易。正如我们所见,您需要存储索引和数组名称以及集合中元素的值。因此,在我看来,最好的选择是将这两个数组合并到一个字典中,其中键将是数字的值,值将为 [ArrayName + Item of item] (fe width0,height1等等......)

所以,让我们将这些数组合并在一个字典中:

int[] width = new int[2] { 10, 20 };
int[] height = new int[2] { 30, 40 };

var widthDictionary = width.ToList().Select((number, index) => new { index, number })
                           .ToDictionary(key => key.number, value => string.Format("width{0}", value.index));
var heightDictionary = height.ToList().Select((number, index) => new { index, number })
                           .ToDictionary(key => key.number, value => string.Format("height{0}", value.index));

// And here is the final dictionary
var totalDictionary = widthDictionary.Union(heightDictionary);

然后将此方法添加到您的班级:(source

public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
    return from m in Enumerable.Range(0, 1 << list.Count)
           select
               from i in Enumerable.Range(0, list.Count)
               where (m & (1 << i)) != 0
               select list[i];
}

然后将您的字典作为参数发送到此方法,并在Select()方法的帮助下根据需要投影此集合:

 var sumOfCombinations = GetPowerSet(totalDictionary.ToList())
              .Where(x => x.Count() > 0)
              .Select(x => new
                        {
                           Numbers = x.Select(pair => pair.Key).ToList(),
                           DisplayValues = x.Select(pair => pair.Value).ToList()
                        })
              .ToList();

最后,您可以显示预期结果:

sumOfCombinations.ForEach(x =>
{
      x.Numbers.ForEach(number => Console.Write("{0} ", number));
      x.DisplayValues.ForEach(displayValue => Console.Write("{0} ", displayValue));
      Console.WriteLine();
});

结果是:

enter image description here

答案 1 :(得分:0)

这是@Farhad Jabiyev的回答。

声明一个名为IndexValuePair的类。并在foreachwidthList上使用heightList。填写指数&#39;项目实例的属性。

注意:索引是一个字符串。


班级&amp;静态功能

    public class IndexValuePair
    {
        public string Index {get;set;}
        public int Value {get;set;}
    }

    public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
    {
         return from m in Enumerable.Range(0, 1 << list.Count)
               select
                     from i in Enumerable.Range(0, list.Count)
                     where (m & (1 << i)) != 0
                     select list[i];
    }

主要(控制台

    static void Main(string[] args)
    {
        int[] width = new int[2] { 10, 20 };
        int[] height = new int[2] { 30, 40 };

        var wholeList = width.Select(val => new IndexValuePair() { Index = "width", Value = val }).ToList();
        var heightList = height.Select(val => new IndexValuePair() { Index = "height", Value = val }).ToList();

        var iteration = 0;
        wholeList.ForEach(ivp => { ivp.Index = ivp.Index + count; count = iteration + 1; });
        iteration = 0;
        heightList.ForEach(ipv => { ivp.Index = ivp.Index + count; count = iteration + 1; });

        wholeList.AddRange(heightList);

        var sumOfCombinations = GetPowerSet(wholeList).Where(x => x.Count() > 0)
             .Select(x => new { Combination = x.ToList(), Sum = x.Sum(ivp => ivp.Value) }).ToList();

        StringBuilder sb = new StringBuilder();
        sumOfCombinations.ForEach(ivp =>
        {
            ivp.Combination.ForEach(pair => sb.Append(string.Format("{0} ", pair.Value)));
            sb.Append(string.Format("= {0} = ", x.Sum));
            ivp.Combination.ForEach(pair=> sb.Append(string.Format("{0} + ", pair.Index)));
            sb.Length -= 3;
            Console.WriteLine(sb);
            sb.Clear();
        });

        var key = Console.ReadKey();
    }