This is my first post here so forgive any formatting errors and the like.
So basically I'm having difficulty implementing a method that takes a given array and rotates it 90 degrees clockwise. We're supposed to implement all given methods in terms of an attribute "imp" like so:
class Matrix {
int[][] imp;
/* All methods in Matrix are implemented in terms of ’imp’ */
}
This is what I have so far in my method implementation:
/**
* <p> Rotate the matrix by 90 degrees.
* <p> The old 1st row becomes the new last column,
* the old 2nd row becomes the new 2nd last column, and so on.
* <p> Hint: attribute 'imp' should be reassigned to a new matrix.
* <p> See TestMatrix class for how this method can be used.
*/
public void rotateClockwise() {
int rows = imp.length;
int cols = imp[0].length;
int[][] m2 = new int[cols][rows];
int i = 0;
int j = 0;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
m2[i][rows - 1 - i] = imp[i][j];
}
}
imp = m2;
}
This is the test case being used to test my method:
@Test
public void test18_RotateClockwise() {
Matrix m1 = new Matrix(3, 4);
int[] nr0 = {1 , 2 , 3 , 4 };
int[] nr1 = {5 , 6 , 7 , 8 };
int[] nr2 = {9 , 10, 11, 12};
m1.setRow(0, nr0);
m1.setRow(1, nr1);
m1.setRow(2, nr2);
int[] nc0 = {9, 10, 11, 12};
int[] nc1 = {5, 6 , 7 , 8 };
int[] nc2 = {1, 2 , 3 , 4 };
int[] nr0_ = {12, 11 , 10 , 9 };
int[] nr1_ = {8 , 7 , 6 , 5 };
int[] nr2_ = {4 , 3 , 2 , 1 };
m1.rotateClockwise();
assertArrayEquals(nc0, m1.getColumn(0));
assertArrayEquals(nc1, m1.getColumn(1));
assertArrayEquals(nc2, m1.getColumn(2));
m1.rotateClockwise();
assertArrayEquals(nr0_, m1.getRow(0));
assertArrayEquals(nr1_, m1.getRow(1));
assertArrayEquals(nr2_, m1.getRow(2));
}
I understand what the test case is trying to do, and my code compiles and doesn't have any exceptions or errors, but I'm getting the wrong output like so:
arrays first differed at element [0]; expected:<9> but was:<0>
I'm assuming this means that I'm basically rotating an empty array. I guess my question is how do I get the array from the test case into my method to rotate it? I tried using getRow and getColumn methods but I get an error telling me I can't call those methods on the attribute imp. Any help is appreciated. Thanks!