开发者

Copy one jagged array ontop of another

How cou开发者_JAVA技巧ld 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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜