简体   繁体   中英

How to check in 2d array if all elements in row and column are the same?

I am trying to write a code in java that would look if all elements in a row and column are the same and print out the indexes of it.

So for example if I had two dimensional array of

{ 1, 0, 0, 0, 0}
{ 1, 0, 0, 0, 0}
{ 1, 1, 1, 1, 1}

I want to print out 2,0 which means that in the row 2 all the elements are the same and in column 0 all the elements are the same too and they are equal to each other.

I was trying to do it with for statements

int[][] array_1 = { {1}, 
                    {1} };
for(int row=0; row<array.length-1; row++){
    for (int col=0; col<array[0].length-1; col++){
        if(array[row][col]==array[row+1][col]&&
           array[row][col]==array[row][col+1]&&
           array[row][col]==array_1[0][0]) {
             System.out.print(row);
             System.out.println(col);      
        }
    }
}

but it does not work because it does not check all the rows and columns, it stops somewhere in the middle and I have no idea what that is happening.

Do you have any suggestions?

You can do this by separating the methods.
First you can write a tranpose method

public static int[][] transpose(int[][] A) {
        int m = A.length;
        int n = A[0].length;
        int[][] C = new int[n][m];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                C[j][i] = A[i][j];
        return C;
    }

Then,you can write this method to check the rows and the columns.If row's elements or column's elements are different,this method return false.Else return true.

public static boolean rowColEquals(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int x = array[0];
            if (x != array[i])
                return false;
        }
        return true;
    }

And Finally, you can write this method to find answer.

public static void findEquals(int[][] array) {
        for (int i = 0; i < array.length; i++) {
            if (rowColEquals(array[i])) {
                System.out.println("All " + array[i][0] + " is equal on row "
                        + i);
            }
        }
        array = transpose(array);
        for (int i = 0; i < array.length; i++) {
            if (rowColEquals(array[i])) {
                System.out.println("All " + array[i][0] + " is equal on colomn "
                        + i);
            }
        }
    }

main method is below

public static void main(String[] args) {
int[][] y = { { 1, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1 } };
        findEquals(y);
    }

and output will be following.

All 1 is equal on row 2
All 1 is equal on colomn 0

One approach would be:

  • Find all the equal rows. Put their indices into some kind of Collection (eg, a Set or List).
  • Find all the equal columns. Put their indices into another Collection.
  • For each equal row, for each equal column, print row, column .

The result includes all the combinations of one member of the equal rows collection paired with one member of the equal columns collection. If it did not, then either the row or column could not be equal.

I think what you are trying to do here is get all the rows and columns which have identical elements, and then returning a combination of those where row and column elements are equal.

So, for instance, if your array was-

{ 1, 0, 0, 1, 0}
{ 1, 0, 0, 1, 0}
{ 1, 1, 1, 1, 1}

Then it should return (2,0) and (2,3).

Now one thing to notice here is that there can only be one type of such intersection possible, ie, if there is a column of all 1s and a column of all 2s, then it is not possible to get a row of either all 1s or all 2s.

Therefore, you should check each column for consistency (all identical elements) and check whether there are more than 1 kind of columns where all elements are same (that is, consistent columns with different numerical values).

If yes, then you won't get an answer, if no, then you should find rows that are consistent (identical elements), and whose values are equal to the element from the columns.

Multiple flaws in the logic here.The most obvious one is

`if(array[row][col]==array[row+1][col]&&
   array[row][col]==array[row][col+1]&&
   array[row][col]==array_1[0][0]) {
   **System.out.print(row);
   System.out.println(col);**                    
 } 

`

You are not even waiting to check the entire row vs column. Also, you compare

array[row][col]==array_1**[0][0]** .

Andy's suggestion is brute force but should get you started. You can optimize the algorithm.

This is how I'd do it:

public void findIntersection ( Object[][] a ) {

    Object knownIntersectionValue = null;
    rowLoop: for (int i = 0; i < a.length; i++ ) {
        final Object candidateValue = a[i][0];
        if ( knownIntersectionValue != null && !candidateValue.equals(knownIntersectionValue) ) {
            // This cannot be an intersection, because all existing intersections must share the same value.
            continue rowLoop;
        }
        ArrayList<Integer> candidateColumns = new ArrayList<Integer>();
        // Loop through columns in the current row
        columnLoop: for ( int j = 0; j < a[0].length; j++ ) {
            if ( ! a[i][j].equals(candidateValue ) ) {
                // We've hit a column with a different value -- no intersections on this row!
                continue rowLoop;
            }
            // The column has the same value as the 1st column, so the current element MAY be an intersection.
            // Check all the rows for the column
            for ( int k = 0; k < a.length; k++ ) {
                if ( ! a[k][j].equals(candidateValue )) {
                    // No, the row, column is not an intersection
                    continue columnLoop;
                }
            }
            // If we get here, then column J is a potential intersection
            // We won't know until we finish checking the row
            candidateColumns.add(j);
        }
        // Print the intersections we've found for the current row
        for ( Integer j : candidateColumns ) {
            System.out.println("Intersection at " + i + ", " + j);
            if ( knownIntersectionValue == null ) {
                knownIntersectionValue = a[i][j];
            }

        }
    }
}

I got how to implement it and I think its easier then the one posted here.

I do not want to post the code, but the algorithm would be to have a for loop going through the column and finding the one which would be equal to 1.

After that having another for loop going through rows and finding where it is equal to 1.

remembering the indexes and printing them out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM