I'm trying to check if two columns of a square matrix are equal. The function is working, but I want to reduce the complexity by using two for instead of three. It's possible? I tried a lot and I couldn't.
int a=0;
boolean equalColumns=false;
for(int k=0;k<this.getRows()-1;k ){
for(int i=k;i<this.getRows()-1;i ){
for(int j=0;j<this.getColumns();j ){
if(this.getElement(j, k)==this.getElement(j, i 1)){
a ;
}
}
if(a==this.getColumns()){
equalColumns=true;
}
}
}
CodePudding user response:
Maybe I didn't understand completely your question; if you have a nXn matrix called M and you want to check if col1 and col2 are equals you can do this:
for(int row = 0; row<M.lenght;row )
if (M[row][col1] != M[row][col2]) return false;
return true;
CodePudding user response:
I would write a method to check on two columns.
- this uses two loops to check each column against the others.
- if any return true, the loop short circuits and displays the result.
int n = 8;
boolean result = false;
int[][] mat = new int[n][n];
outer: for (int c1 = 0; c1 < n - 1; c1 ) {
for (int c2 = c1 1; c2 < n; c2 ) {
if (result = equalColumns(mat, c1, c2)) {
break outer;
}
}
}
if (result) {
System.out.println("contains equal columns");
}
- this just takes the matrix and the columns to be checked and compares them.
- it also short circuits as soon as a mismatch is found.
public static boolean equalColumns(int[][] mat, int cola,
int colb) {
for (int row = 0; row < mat.length; row ) {
if (mat[row][cola] != mat[row][colb]) {
return false;
}
}
return true;
}