简体   繁体   中英

Copy one jagged array ontop of another

How could I accomplish copying one jagged array to another? For instance, I have a 5x7 array of:

0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0

and a 4x3 array of:

0,1,1,0
1,1,1,1
0,1,1,0

I would like to be able to specify a specific start point such as (1,1) on my all zero array, and copy my second array ontop of it so I would have a result such as:

0, 0, 0, 0, 0, 0, 0
0, 0, 1, 1, 0, 0, 0
0, 1, 1, 1, 1, 0, 0
0, 0, 1, 1, 0, 0, 0
0, 0, 0, 0, 0, 0, 0

What would be the best way to do this?

Due to the squared nature of your example, this seems more fitting of a 2D array instead of jagged. But either way, you could certainly do it the old fashioned way and loop over it. Something like (untested)

for (int i = 0; i < secondArray.Length; i++)
{
    for (int j = 0; j < secondArray[0].Length; j++)
    {
        firstArray[startingRow + i][startingColumn + j] = secondArray[i][j];
    }
}

Edit: Like Mark, I also had a slight improvement, slightly different but along the same lines.

for (int i = 0; i < secondArray.Length; i++)
{
    secondArray[i].CopyTo(firstArray[startingRow + i], startingColumn);
}

This should work even if your inputs are not rectangular:

void copy(int[][] source, int[][] destination, int startRow, int startCol)
{
    for (int i = 0; i < source.Length; ++i)
    {
        int[] row = source[i];
        Array.Copy(row, 0, destination[i + startRow], startCol, row.Length);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM