views:

85

answers:

2

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?

+2  A: 

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);
}
Anthony Pegram
+1: With your edit, your solution also works for non-rectangular arrays. :)
Mark Byers
+2  A: 

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);
    }
}
Mark Byers
Good edit. I was about to add `secondArray[i].CopyTo(firstArray[startingRow + i], startingColumn);` instead of my inner loop. You beat me!
Anthony Pegram
@Anthony: Actually CopyTo is very good here - you should make that change.
Mark Byers