我正在用 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 个独特的总和。
有人对此有聪明的解决方案吗?我自己尝试了一些变体,但我无法理解这一点。
亲切的问候, 彼得
最佳答案
有一种稍微更数学的方法来计算它,而不是蛮力。
假设一行中的每个值将被求和 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
}
关于c# - 如何计算二维数组中唯一组合的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788549/