【问题标题】:How to calculate sum of uniqe combinations in 2-dimensional array如何计算二维数组中唯一组合的总和
【发布时间】:2019-05-16 05:53:28
【问题描述】:

我正在 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 个独特的和需要计算。

有人对此有聪明的解决方案吗?我自己尝试了一些变体,但我无法理解这一点。

亲切的问候, 彼得

【问题讨论】:

  • 我通常只是通过类似这样的递归来暴力破解。
  • 你能提供几个非唯一组合的例子吗?

标签: c# arrays algorithm


【解决方案1】:

有一种稍微更数学的方法来解决这个问题,而不是蛮力。

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

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
}

【讨论】:

  • 这在数字与示例中完全相同时有效。我确实理解不同的问题,但似乎彼得正在寻找 rhis。干得好!
【解决方案2】:

给你:

class Program
    {
        static void Main(string[] args)
        {
            int[][] values = new int[5][];
            values[0]= new int[] { 1, 32, 1024 };
            values[1] = new int[] { 2, 64, 2048 };
            values[2] = new int[] { 4, 128, 4096 };
            values[3] = new int[] { 8, 256, 8192 };
            values[4] = new int[] { 16, 512, 16384 };

            int[] result = values[0]; 

            for(int i = 1; i < values.GetLength(0); i++)
            {
                result = Multiply2Arrays(result, values[i]);
            }
        }

        private static int[] Multiply2Arrays(int[] array1, int[] array2)
        {
            int[] result = new int[array1.Length * array2.Length];
            int counter = 0;
            for (int i = 0; i < array1.Length; i++)
            {
                for (int j = 0; j < array2.Length; j++)
                {
                    result[counter] = array1[i] + array2[j];
                    counter++;
                }
            }
            return result;
        }
    }

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 2021-12-23
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多