Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a large Array be split into smaller arrays?

Tags:

c#

algorithm

Given a large array how can it be split into smaller arrays with the size of the smaller arrays specified as an argument of the method?

For instance, given numbers, what would Split's implementation be?

int[] numbers = new int[7845];

int[][] sectionedNumbers = numbers.Split(1000);

sectionedNumbers.Length; //outputs 8
sectionedNumbers[7].Length; //outputs 845
like image 849
Bob Avatar asked Dec 05 '22 04:12

Bob


1 Answers

You can do it with an extension method:

using System;

static class Program
{
    static T[][] Split<T>(this T[] arrayIn, int length)
    {
        bool even = arrayIn.Length%length == 0;
        int totalLength = arrayIn.Length/length;
        if (!even)
            totalLength++;

        T[][] newArray = new T[totalLength][];
        for (int i = 0; i < totalLength;++i )
        {
            int allocLength = length;
            if (!even && i == totalLength - 1)
                allocLength = arrayIn.Length % length;

            newArray[i] = new T[allocLength];
            Array.Copy(arrayIn, i * length, newArray[i], 0, allocLength);
        }
        return newArray;
    }

    static void Main(string[] args)
    {
        int[] numbers = new int[8010];
        for (int i = 0; i < numbers.Length; ++i)
            numbers[i] = i;

        int[][] sectionedNumbers = numbers.Split(1000);

        Console.WriteLine("{0}", sectionedNumbers.Length);
        Console.WriteLine("{0}", sectionedNumbers[7].Length);
        Console.WriteLine("{0}", sectionedNumbers[1][0]);
        Console.WriteLine("{0}", sectionedNumbers[7][298]);
        Console.ReadKey();
    } 
}

This prints:

9
1000
1000
7298
like image 189
Reed Copsey Avatar answered Jan 09 '23 03:01

Reed Copsey