Array segments

Sometimes we want to split an array in various segments and perform some processing on each of segment. ArraySegment class is useful in that.

In below program we create a segment array by combining subsets of elements from both arrays ar1 and ar2. First 3 elements of ar1 is picked and element 4, 5, 6 of array ar2 is picked.

Then we define an array of 2 segments filling elements from both the above mentioned subsets. The ArraySegment constructor takes two three parameters which are the array address, the starting index value of array, and number of items to traverse including starting index.

The array of segment is passed to function SumOfSegments. In this function, first an external foreach loop is run on segments, then using for loop, elements of each segment are traversed with respect to offset and count and their sum is computed, and stored in variable ‘sum’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
    
    class Program
    {

        static void Main(string[] args)
        {
            int[] ar1 = { 1, 4, 5, 11, 13, 18 };
            int[] ar2 = { 3, 4, 5, 18, 21, 27, 33 };

            var segments = new ArraySegment<int>[2] { new ArraySegment<int>(ar1, 0, 3), 
                                                      new ArraySegment<int>(ar2, 3, 3) };
            var sum = Program.SumOfSegments(segments);
            Console.Write("{0}", sum);
        }

        static int SumOfSegments(ArraySegment<int>[] segments)
        {
            int sum = 0;

            foreach(var segment in segments)
            {
                for(int i=segment.Offset; i<segment.Offset + segment.Count; i++)
                {
                    sum = sum + segment.Array[i];
                }
            }
            return sum;
        }

        
    }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *