HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaMinor

Search in a 2D array to find if there is a row or a column that contains the word “error” in every cell of that row or column

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
celltheerrorsearchcolumnarrayeverywordthatcontains

Problem

Search in a 2D array to check if there is a column or a row in the 2D Array thats contains all the word “error”, if yes return the index of that row or column else return 0;

Exception: if the row index equals the column index then it does not matter if contains the word "error" or not. FYI, n is the size of 2D array (number of rows = number of columns)

I wrote this code and I want to check with you if you agree with the logic:

int search(int n, String[][] myArray) {
        int j, k;
        boolean isError;

        //To search per ROW
        for (int i = 1; i <= n; i++) {
            j = 1;
            isError = true;

            while (j <= n && isError) {
                if ((i != j) && (myArray[i][j] != "error")) {
                    isError = false;
                }

                if (j == n && isError) {
                    return i;
                } else {
                    j++;
                }
            }
        }//end for loop

        //To search per COLUMN
        for (int i = 1; i <= n; i++) {
            k = 1;
            isError = true;

            while (k <= n && isError) {
                if ((i != k) && (myArray[k][i] != "error")) {
                    isError = false;
                }

                if (k == n && isError) {
                    return i;
                } else {
                    k++;
                }
            }
        }//end for loop

        return 0;

    }

Solution

My Java is a bit rusty but I'm not seeing any logical issues with the code doing what you want it to.

Since you return just the row or column index, the caller can't tell from that if the match was a row or a column.

Context

StackExchange Code Review Q#106071, answer score: 2

Revisions (0)

No revisions yet.