I have an assignment to implementthe matrix class and a method that checks if the matrix is symmetric. The method has to be recursive and then I have to calculate its complexity. After I have to transform the recursive function to its iterative version.
For now this is how my matrix class looks like:
public class Matrix<T> {
private int m, n;
private T[][] data;
public Matrix(int m, int n) {
this.m = m;
this.n = n;
}
public Matrix(T[][] data) {
this.data = data;
}
public boolean isSymmetric() {
if (m != n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (data[i][j] != data[j][i]) {
return false;
}
}
}
return true;
}
return false;
}
public boolean isSymmetric(int i, int j) {
if (i < 0 && j < 0) return true;
else {
return isSymmetric(i - 1, j - 1);
}
}
public T get(int i, int j) {
return data[i][j];
}
public void set(int i, int j, T value) {
data[i][j] = value;
}
public int[] getSize() {
return new int[]{m, n};
}
@Override
public String toString() {
String rep = "";
for (int i = 0; i < m; i++) {
rep += "( ";
for (int j = 0; j < n; j++) {
rep += data[i][j].toString() + "\t";
}
rep += ")\n";
}
return rep;
}
}
I have a iterative version of the isSymmetric()
function, but I cannot get the recursive one.
In the recursive version, you forgot to add a check to see if the two elements are equal. Without it, there is no case where the method would return
false
.