java 如果行和列中的所有元素都相同,如何检查二维数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33530721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:49:07  来源:igfitidea点击:

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

javaarraysalgorithmmultidimensional-array

提问by ZpCikTi

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.

我正在尝试用 java 编写一个代码,它会查看行和列中的所有元素是否相同并打印出它的索引。

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.

我想打印出 2,0 这意味着在第 2 行中所有元素都相同,在第 0 列中所有元素也相同并且它们彼此相等。

I was trying to do it with for statements

我试图用 for 语句来做

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?

你有什么建议吗?

回答by ZpCikTi

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.

然后,您可以编写此方法来检查行和列。如果行元素或列元素不同,则此方法返回false。否则返回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

回答by Andy Thomas

One approach would be:

一种方法是:

  • Find all the equal rows. Put their indices into some kind of Collection (e.g., 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.
  • 找出所有相等的行。将它们的索引放入某种集合(例如,集合或列表)中。
  • 找出所有相等的列。将它们的索引放入另一个集合中。
  • 对于每个相等的行,对于每个相等的列,打印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.

结果包括等行集合的一个成员与等列集合的一个成员配对的所有组合。如果不是,则行或列不能相等。

回答by goelakash

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).

然后它应该返回 (2,0) 和 (2,3)。

Now one thing to notice here is that there can only be one type of such intersection possible, i.e., 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.

现在要注意的一件事是,这种交集只能存在一种类型,即,如果有一列全 1 和一列全 2,则不可能得到一行全 1 或都是 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).

因此,您应该检查每一列的一致性(所有相同的元素),并检查是否有超过 1 种所有元素都相同的列(即具有不同数值的一致列)。

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.

如果是,那么您将不会得到答案,如果不是,那么您应该找到一致(相同元素)的行,并且其值等于列中的元素。

回答by Umar Ashraf

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]**.

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

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

安迪的建议是蛮力,但应该让你开始。您可以优化算法。

回答by Matthew McPeak

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];
            }

        }
    }
}

回答by Matthew McPeak

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.

我不想发布代码,但算法是让 for 循环遍历列并找到等于 1 的那个。

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

之后有另一个 for 循环遍历行并找到它等于 1 的位置。

remembering the indexes and printing them out.

记住索引并打印出来。