Search code examples
c#arrayspaddingzero-padding

Zero padding a 2D array in C#


I currently have an issue with zero padding my 2d Array. I want to transfer my current data in my array to a new array, which is the exact same array but with a border of 0's around it. Example:

|1 2 3|

|4 5 6|

|7 8 9|

Should become

|0 0 0 0 0|

|0 1 2 3 0|

|0 4 5 6 0|

|0 7 8 9 0|

|0 0 0 0 0|

 int[,] Array = new int[,] { { 1, 2, 3 }, { 3, 4, 5 }, { 6, 7, 8 } };
        
        int[,] ArrayZeroPad = new int[Array.GetLength(0) + 2, Array.GetLength(1) + 2];
        for (int y = 0; y < Array.GetLength(1); y++)
        {

            for (int x = 0; x < ArrayZeroPad.GetLength(0); x++)
            {
                if (y == 0)
                { ArrayZeroPad[y, x] = 0; }
                else if (y == ArrayZeroPad.GetLength(1))
                { ArrayZeroPad[y, x] = 0; }
                else if (x == 0)
                {
                    ArrayZeroPad[y, x] = 0;

                }
                else if (x == ArrayZeroPad.GetLength(0))
                { ArrayZeroPad[y, x] = 0; }
                else ArrayZeroPad[y, x] = Array[y, x];
            }
        }
        for (int y = 0; y < ArrayZeroPad.GetLength(1); y++)
        {
            Console.WriteLine();
            for (int x = 0; x < ArrayZeroPad.GetLength(0); x++)
            { Console.Write(ArrayZeroPad[y, x]); }
            Console.ReadLine();
        }
    }

This is what I have come to thus far, but I keep getting stuck on out of bounds errors, is there anyone who could work this out for me with some explanation?

Kind regards, D.


Solution

  •         int[,] Array = new int[,] { { 1, 2, 3 }, { 3, 4, 5 }, { 6, 7, 8 } };
            int[,] ArrayZeroPad = new int[Array.GetLength(0) + 2, Array.GetLength(1) + 2];
    
            for (int x = 0; x < ArrayZeroPad.GetLength(0); x++)
            {
                for (int y = 0; y < ArrayZeroPad.GetLength(0); y++)
                {
                    //First row and last row
                    if (x == 0 || x == ArrayZeroPad.GetLength(0) - 1)
                        ArrayZeroPad[x, y] = 0;
                    else
                    {
                        //Fist column and last column
                        if (y == 0 || y == ArrayZeroPad.GetLength(0) - 1)
                            ArrayZeroPad[x, y] = 0;
                        else
                        {
                            //Content
                            ArrayZeroPad[x, y] = Array[x-1, y-1];
                        }
                    }
                }
            }