aLittleMind
aLittleMind

Reputation: 193

Compare elements of rows or columns in 2D array (Java)

I have a String[][] field. For example, it may look like:

[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]
[xy] [xy] [xy] [xy] [xy]

Number of rows and columns is equal, but number may be different each time. I need to check if the values of elements of entire row or entire column are equal. I have written some bad code for 3x3 field to check line, here it is:

public boolean checkHorizontal(String[][] field) {
        boolean value = false;
        int x = 0;
        for (int i = 0; i < field.length; i++) {
            if (field[i][x].equals(field[i][x + 1]) &&
                    field[i][x + 1].equals(field[i][x + 2]) &&
                    !field[i][x].equals("[something]")) {
                value = true;
            }
        }
        return value;
    }

But it's not universal way to check line, because we may have a matrix of different size (and need to add x + 3, x + 4, x + 5, etc.) Is there any effective way to compare entire row/column of 2D array?

Upvotes: 0

Views: 15283

Answers (2)

Stefan Nolde
Stefan Nolde

Reputation: 211

The answer of @quidproquo actually checks if all fields are equal, but it's pretty easy to adapt the solution to a single row or column:

public boolean isEqual(String[][] data, int rowColumn, boolean row){
    int i = 1;
    int limit = (row) ? data[0].length : data.length;
    while(i<limit){
         if ((row) ? !data[rowColumn][i].equals(data[rowColumn][0])
             : !data[i][rowColumn].equals(data[0][rowColumn]))
             return false;
    }
    return true;
}

Upvotes: 0

Bill
Bill

Reputation: 4646

To check all rows:

for(int i = 0; i < field.length; i++){
    for(int j = 1; j < field[i].length; j++){
        if(!field[i][0].equals(field[i][j])){
            return false;
        }
    }
}

return true;

Upvotes: 3

Related Questions