数组项的累积总和 [英] Cumulative sum of array items

查看:67
本文介绍了数组项的累积总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个排序数组,其值如下:

I have an sorted array having values like below: I need to calculate total as below:

方案1-数组值12,15,17

12+15 = 27 
27+17 = 44 
44+27 = 71
Total = 71

方案2数组值12,15,17,19

12+15 = 27
27+17 = 44
44+19 = 63
27+44+63 = 134

总数= 134

方案3数组值12,15,17,19,23

12+15 = 27
27+17 = 44
44+19 = 63
63+23 = 86
27+44+63+86 = 220

总数= 220

方案4,直到N个数组值12,15,17,19,23 ..... N

我必须把上面的逻辑带到 C# 代码中

I have to bring the above logic to C# code

我写的如下:

  int[] myNumbers = new int[] { 100,250,1000};

            Array.Sort(myNumbers);
            int sum = 0;
            int temp = 0;

            foreach (int y in myNumbers)
            {
                sum = sum + y;              
            }

            for(int i=0;i<myNumbers.Length-1;i++)
            {
               temp = temp + myNumbers[i];      
            }

           sum = sum + temp;

           Console.Write(sum);  

上面的代码适用于数组值100,250,1000

The above code works fine for array values 100,250,1000

但是对于其他任何数组值

But it fails for any other array values

需要帮助!

推荐答案

选项1

因此,如果您希望如示例中那样获得准确的结果,则可以使用此方法.它将返回一个部分和数组,您可以稍后对其求和以得到结果:

So if you want to get exact results as in your examples, you can use this method. It will return you an array of partial sums, that you can later sum up to get the result:

private static long[] CumulativeSums(long[] values)
{
    if (values == null || values.Length <= 1) return new long[0];

    var results = new long[values.Length];
    results[0] = values[0] + values[1];

    for (var i = 1; i < values.Length - 1; i++)
    {
        results[i] = results[i - 1] + values[i + 1];
    }

    return results;
}

并以此方式使用:

var numbers = new long[] { 12, 15, 17, 19 };
var sumOfCumulativeSums = CumulativeSums(numbers).Sum();

sumOfCumulativeSums 将为134.

选项2

但累积和的实际正确表示是:a, a+b, a+b+c, ....因此,如果您想要方法的正确表示形式返回正确的累计和,则可以改用以下方法:

But the actual correct representation of cumulative sum is: a, a+b, a+b+c, .... So if you want the correct representation of method that returns you proper cumulative sums, you can use this method instead:

public static long[] CumulativeSums(long[] values)
{
    if (values == null || values.Length == 0) return new long[0];

    var results = new long[values.Length];
    results[0] = values[0];

    for (var i = 1; i < values.Length; i++)
    {
        results[i] = results[i - 1] + values[i];
    }

    return results;
}

修改

希望这可以帮助您以任何一种方式解决您的问题,如果您对代码有任何疑问或修改,请提出.

Hope this helps you to solve your problem in either of ways, and if you have any questions or edits about the code, please ask.

这篇关于数组项的累积总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆