Recipe5.3.Reversing a Two-Dimensional Array


Recipe 5.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 operation.

Solution

Use the following Reverse2DimArray<T> method:

 public static void Reverse2DimArray<T>(T[,] theArray) {     for (int rowIndex = 0; rowIndex <= (theArray.GetUpperBound(0)); rowIndex++)     {         for (int colIndex = 0;             colIndex <= (theArray.GetUpperBound(1) / 2);             colIndex++)         {             T 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<T> 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<T> 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

See Recipes 5.2 and 5.4.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net