DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 9.3 Reversing a Two-Dimensional Array

Problem

You need to reverse each row in a two-dimensional array. The Array.Reverse method does not support this.

Solution

Use two loops; one to iterate over rows, the other to iterate over columns:

public static void Reverse2DimArray(int[,] theArray)
{
    for (int rowIndex = 0; 
         rowIndex <= (theArray.GetUpperBound(0)); rowIndex++)
    {
        for (int colIndex = 0; 
             colIndex <= (theArray.GetUpperBound(1) / 2); colIndex++)
        {
            int tempHolder = theArray[rowIndex, colIndex];                        
            theArray[rowIndex, colIndex] = 
              theArray[rowIndex, theArray.GetUpperBound(1) - colIndex];   
            theArray[rowIndex, theArray.GetUpperBound(1) - colIndex] = 
              tempHolder;      
        }
    }
}

Discussion

The following TestReverse2DimArray method shows how the Reverse2DimArray method is used:

public static void TestReverse2DimArray( )
{
    int[,] someArray = 
      new int[5,3] {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};

    // Display the original array
    foreach (int i in someArray)
    {
        Console.WriteLine(i);
    }
    Console.WriteLine( );

    Reverse2DimArray(someArray);

    // Display the reversed array
    foreach (int i in someArray)
    {
        Console.WriteLine(i);
    }
}

This method displays the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

3     Note that each row of 3 elements are reversed
2
1
6     This is the start of the next row
5
4
9
8
7
12
11
10
15
14
13

The Reverse2DimArray method uses the same logic presented in the previous recipe to reverse the array; however, a nested for loop is used instead of a single for loop. The outer for loop iterates over each row of the array (there are five rows in the someArray array). The inner for loop is used to iterate over each column of the array (there are three columns in the someArray array). The reverse logic is then applied to the elements handled by the inner for loop, which allows each row in the array to be reversed.

See Also

Recipe 9.2 and Recipe 9.4.

    [ Team LiB ] Previous Section Next Section