如何计算二维数组中的uniqe组合之和

时间:2018-12-15 00:35:37

标签: c# arrays algorithm

我正在用C#创建一个函数来计算数组中值的唯一组合的和。

我有一个带有以下值的二维数组:

1  | 32  | 1024
2  | 64  | 2048
4  | 128 | 4096
8  | 256 | 8192
16 | 512 | 16384

对于每一行,我选择一列,然后对这些值求和,例如:

(1)  | 32    | 1024
2    | (64)  | 2048
4    | (128) | 4096
8    | 256   | (8192)
(16) | 512   | 16384


1 + 64 + 128 + 8192 + 16 = 8401

我要为所有唯一的行和列组合计算此值。如我所见,将要计算3 ^ 5 = 243个唯一和。

有人对此有一个明智的解决方案吗?我自己尝试了一些变体,但是我对此一无所知。

亲切的问候, 彼得

2 个答案:

答案 0 :(得分:2)

您在这里:

ng

答案 1 :(得分:2)

有一种数学方法可以解决问题,而不是蛮力。

鉴于行中的每个值将与其他width行中的每一行相加height-1次,您可以执行以下操作:

static void Main(string[] args)
{
    int[,] arr = new int[3, 5];
    int val = 1;
    int total = 0;
    //Both init the array with data, and get the sum of all elements
    for (int c=0; c<3; ++c)
    {
        for(int r=0; r<5; ++r)
        {
            arr[c,r] = val;
            total += val;
            //Console.Write("{0} ", val);
            val <<= 1;
        }
        //Console.WriteLine("");
    }

    //Do the math
    int b = arr.GetLength(0);
    int e = arr.GetLength(1) - 1;
    int power = (int)Math.Pow(b, e);
    total *= power;

    Console.WriteLine(total); //Outputs 2654127
}