Reputation: 1
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;
}
}
}
Upvotes: 0
Views: 946
Reputation: 40057
I would write a method to check on two columns.
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");
}
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;
}
Upvotes: 0
Reputation: 519
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;
Upvotes: 1