Tuesday, 10 September 2013

2d Array that swaps all the integers or characters in opposing rows/columns

2d Array that swaps all the integers or characters in opposing rows/columns

. Write the implementation of the method switchRows. This method receives
a 2-dimensional array of integers and switches the values in opposing
rows. For example, given a 2-dimensional array (shown left, below), the
method should swap its row values (shown right, below) where the values on
the 1st row (index 0) are switched with the values on the 5th row (index
4), and the values on the 2nd row (index 1) are switched with those on the
4th (index 3). Since this example shows an array with odd-numbered rows,
the 3rd row (index 2) did not have an opposing row with which to get
swapped. Nevertheless, the method should work with any 2-dimensional
array.
Write the implementation of the method switchColumns. This method receives
a 2-dimensional array of characters and switches the values in opposing
columns. For example, given a 2-dimensional array (shown left, below), the
method should swap its column values (shown right, below). The method
should work with any 2-dimensional array.
I feel like I'm getting this problem turned around in my head because rows
and columns are easy to mix up. Can someone help show me where I'm going
wrong.
public static void switchRows( int[][] anArray ){
int num = 1;
for(int i = 0; anArray.length > i; i++){
for(int j = 0; anArray[i].length > j; j++){
int[][] temp = new int[anArray.length][anArray[i].length];
temp[i] = anArray[i];
anArray[i] = anArray[anArray.length - num];
anArray[anArray.length - num] = temp[i];
}
num++;
}
}
public static void switchColumns( char[][] anArray ){
int col = 1;
for(int i = 0; anArray.length > i; i++){
for(int j = 0; anArray[i].length > j; j++){
char[][] temp = new char[anArray.length]
[anArray[i].length];
temp[j] = anArray[j];
anArray[j] = anArray[anArray[i].length - col];
anArray[anArray[i].length - col] = temp[j];
}
col++;
}

No comments:

Post a Comment