Reputation: 467
I am having difficulty with this code. I am trying to return a 2d which is the reverse of the input array. I am not sure how to code this correctly. Perhaps someone may have a few suggestions
public class arrays {
int[][] transpose(int[][] a) {
int[][] good = new int[a.length][a.length]; /* assign dimension, I want it to be the same as input */
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a[k].length; k++) { // //nested loop to go through the rows and columns
good[i][k] = a[k][i]; // /// switch elements
}
}
return good;
}
}
Upvotes: 1
Views: 132
Reputation: 31269
You need to think carefully which variable indicates a row, and which one a column. And in which array (a
or good
).
As I switched these around in your code, this improved version does work:
public class Arrays {
static int[][] transpose(int[][] a) {
// Only works if a is rectangular (every row in a has the same number of columns)
int[][] good = new int[a[0].length][a.length];
for (int i = 0; i < a.length; i++) {
// Use a[i].length, not a[k].length because k will be bigger than a.length at some point.
for (int k = 0; k < a[i].length; k++) {
// i = row in 'a', column in 'good'
// k = column in 'a', row in 'good'
good[k][i] = a[i][k];
}
}
return good;
}
}
The problems were:
int[][] good = new int[a.length][a.length];
Here you are creating a square matrix in good
even though the original can be any rectangle shape (different number of rows and columns). You need to switch the number of rows and columns, so new int[a[0].length][a.length]
is a good fix. (Assuming that all rows have an equal number of columns, which is required in a matrix)for (int k = 0; k < a[k].length; k++)
Here k
is going to increase until it is larger than a.length
, and you will get an ArrayIndexOutOfBoundsException
You want to loop over all columns in row i
, so the upper bound is a[i].length
, not a[k]
.good[i][k] = a[k][i]
Remember that i
was the row in a
, not in good
. In good
, it is the column. So you need to swap your i's and k's on both sides of the assignment.Upvotes: 2