Recipe5.4.Reversing a Jagged Array


Recipe 5.4. Reversing a Jagged Array

Problem

The Array.Reverse method does not provide a way to reverse each subarray in a jagged array. You need this functionality.

Solution

Use the ReverseJaggedArray<T> method:

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

Discussion

The following TestReverseJaggedArray method shows how the ReverseJaggedArray<T> method is used:

 public static void TestReverseJaggedArray() {     int[][] someArray =         new int[][] {new int[3] {1,2,3}, new int[6]{10,11,12,13,14,15}};     // Display the original array.     for (int rowIndex = 0; rowIndex < someArray.Length; rowIndex++)     {         for (int colIndex = 0; colIndex < someArray[rowIndex].Length; colIndex++)         {             Console.WriteLine(someArray[rowIndex][colIndex]);         }     }     Console.WriteLine();     ReverseJaggedArray(someArray);     // Display the reversed array.     for (int rowIndex = 0; rowIndex < someArray.Length; rowIndex++)     {         for (int colIndex = 0; colIndex < someArray[rowIndex].Length; colIndex++)         {             Console.WriteLine(someArray[rowIndex][colIndex]);         }     } } 

This method displays the following:

 1 2 3 10 11 12 13 14 15 3  The first reversed subarray 2 1 15  The second reversed subarray 14 13 12 11 10 

The logic used to reverse each subarray of a jagged array is very similar to the reversal logic discussed in the previous recipe. The ReverseJaggedArray<T> method uses the same basic logic presented in Recipe 5.2 to reverse each element in the array; however, a nested for loop is used instead of a single for loop. The outer for loop iterates over each element of the first dimensioned array of the jagged array (there are two elements in this array). The inner for loop is used to iterate over each element contained within the second dimensioned array of the jagged array. The reverse logic is then applied to the elements handled by the inner for loop. This allows each array contained by the first dimensioned array in the jagged array to be reversed.

See Also

See Recipes 5.2 and 5.3.



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