如何能大阵被分裂成更小的阵列?阵列、更小、能大阵被

2023-09-11 02:15:01 作者:月光下等你

由于大阵怎么能分裂成更小的阵列与指定为方法的参数?

小数组的大小

例如,提供的数字,你会分割的实现呢?

  INT []号=新INT [7845];

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

sectionedNumbers.Length; //输出8
sectionedNumbers [7] .Length; //输出845
 

解决方案

您可以用扩展方法做到这一点:

 使用系统;

静态类节目
{
    静态T [] []分割< T>(这件T [] arrayIn,INT的长度)
    {
        布尔甚= arrayIn.Length%长度== 0;
        INT totalLength = arrayIn.Length /长;
        如果(!连)
            totalLength ++;

        T [] [] newArray =新T [totalLength] [];
        的for(int i = 0; I< totalLength ++ I)
        {
            INT allocLength =长度;
            如果(甚至与功放;&安培;!我== totalLength  -  1)
                allocLength = arrayIn.Length%的长度;

            newArray [我] =新的T [allocLength]
            Array.Copy(arrayIn,I *长度,newArray [I],0,allocLength);
        }
        返回newArray;
    }

    静态无效的主要(字串[] args)
    {
        INT []号=新INT [8010];
        的for(int i = 0; I< numbers.Length ++ 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();
    }
}
 
CAD怎么把一个大方块,分解为若干个小方块

这将打印:

  9
1000
1000
7298
 

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

解决方案

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