Home > Back-end >  Aggregate the elements of an array to not be larger than a defined value
Aggregate the elements of an array to not be larger than a defined value

Time:10-27

I have an array, say

var myArray = new[] { 1, 2, 3, 1, 3, 1, 3, 1, 2, 1, 2, 7};

I want to get a new list that stores the sum of the elements of this array in a way that when I add the first element to the next, it takes the result forward and then adds to the next etc., but if the sum result is greater than 6, it skips to the next element and starts a new sum but saves the previous sum to the new list.

So, for my array above, I am expecting a result like this 6, 5, 6, 3, 7

How do I go about this?

This is what I have tried. Problem here is that the last element is always skipped. I also worry if this is the perfect way to go about it.

int[] DoAggregate(int[] array)
{
    var prev = 0;
    bool first = true;
    var sum = 0;

    List<int> result = new();
    foreach (var item in array)
    {
        if (first)
        {
            first = false;
        }
        else
        {
            sum = sum   prev;
            if ((sum   item) > 6)
            {
                result.Add(sum);
                sum = 0;
                prev = item;
                continue;
            }
        }
        prev = item;
        
    }
    return result.ToArray();
}

CodePudding user response:

It looks like all you need to do is take into account when sum prev is a value greater than 0 after the loop:

int[] DoAggregate(int[] array)
{
    var prev = default(int);
    bool first = true;
    var sum = 0;

    List<int> result = new();
    foreach (var item in array)
    {
        if (first)
        {
            first = false;
        }
        else
        {
            sum = sum   prev;
            if ((sum   item) > 6)
            {
                result.Add(sum);
                sum = 0;
                prev = item;
                continue;
            }
        }
        prev = item;
        
    }

    sum = sum   prev;
    if (sum > 0)
    {
        result.Add(sum);
    }
    return result.ToArray();
}
  • Related