【问题标题】:Java - 2D array checking diagonal number boardJava - 二维数组检查对角数板
【发布时间】:2016-07-23 13:35:38
【问题描述】:

目前我正在开发一个在 8x8 2D 阵列板上生成随机 0 和 1 的程序。我要做的是检查对角线上的所有数字是否相同(从角开始,而不仅仅是对角线)。

示例:

int[][] array = {
    {0, 0, 0, 0, 0, 0, 0, 1},
    {0, 0, 1, 0, 1, 0, 1, 0},
    {0, 0, 0, 0, 1, 1, 1, 0},
    {0, 0, 0, 0, 1, 1, 1, 0},
    {0, 0, 1, 1, 0, 1, 1, 0},
    {0, 0, 1, 0, 0, 0, 1, 0},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {1, 0, 0, 1, 1, 1, 1, 0}
};

因此,如果碰巧从左上角 (0,0),(1,1)...(7,7) 开始的所有数字都是 0 或 1,那么我必须输出到扫描仪指示即“主对角线为 0”(来自上面的示例)。

同样从这个例子中,我们可以看到,从右上角,数字“1”在左下角对角重复,那么我也必须显示“有一个小对角线 1”。

到目前为止,我已经弄清楚如何生成数字并将其输入到数组中,但我不知道如何检查。这是我目前所拥有的:

public class JavaTest{
// Main method
public static void main(String[] args) {

    int[][] array = {
        {0, 0, 0, 0, 0, 0, 0, 1},
        {0, 0, 1, 0, 1, 0, 1, 0},
        {0, 0, 0, 0, 1, 1, 1, 0},
        {0, 0, 0, 0, 1, 1, 1, 0},
        {0, 0, 1, 1, 0, 1, 1, 0},
        {0, 0, 1, 0, 0, 0, 1, 0},
        {0, 1, 0, 0, 0, 0, 0, 0},
        {1, 0, 0, 1, 1, 1, 1, 0}
    };

    // Print array numbers
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++)
            System.out.print(array[i][j] + " ");
        System.out.println();
    }
    // Print checkers

    checkMajorDiagonal(array);
}
// Check major diagonal 
public static void checkMajorDiagonal(int array[][]) {
    int majDiag;
    boolean isMatching = true;
    int row = 0;
    for(row = 0; row < array.length; row++){
        majDiag = row;
        if(array[row][row] != array[row+1][row+1]){
            isMatching = false;
            break;
        }
    }
    //If all elements matched print output
    if(isMatching)  
        System.out.println("Major diagonal is all " + array[row][row]);
    }
}

虽然到目前为止我所拥有的并没有像我想要的那样工作,因为有一个错误,我仍然需要做小对角线。提前致谢。

【问题讨论】:

    标签: java arrays multidimensional-array 2d


    【解决方案1】:

    已经有很多答案了。这是另一种方法。您走在正确的轨道上,但没有必要通过检查对角线元素和下一个元素等来使事情复杂化。只需使用第一个对角元素检查每个对角元素。一旦发现差异,就停止检查!

     public static void checkDiagonal(int[][] array){
    
         // Start with the assumption that both diagonals are consistent.
         boolean majorConsistent = true; 
         boolean minorConsistent = true;
    
         int length = array.length;
    
         int tempMajor = array[0][0];        // all elements in the Major must be equal to this
         int tempMinor = array[0][length-1]; // all elements in the Minor must be equal to this
    
         // Check major diagonal, and update the boolean if our assumption is wrong.
         for(int i=0; i<length; i++){ 
             if (array[i][i] != tempMajor) { //(0,0);(1,1);(3,3);...
                 majorConsistent = false;
                 break;
             }
         }
    
         // Check minor diagonal, and update the boolean if our assumption is wrong.
         for(int i=0,j=length-1; i<length; i++,j--){
             if (array[i][j] != tempMinor) { //(0,7);(1,6);(2,5);...
                 minorConsistent = false;
                 break;
             }
         }
    
         System.out.println("Major elements all same = "+majorConsistent);
         System.out.println("Minor elements all same = "+minorConsistent);
    
     }
    

    这样,您仍然在进行 O(n) 中的两项检查,并且不需要嵌套 for 循环! 请注意,您可以优化此代码以消除冗余,即具有单个 for 循环等。

    【讨论】:

      【解决方案2】:

      如果您使用的是 Java 8,那么您可能会使用流来执行此操作,而不是手动迭代这些值。这可能是比检查以前的值更直接的方法。

      if (IntStream.range(0, size).map(n -> array[n][n]).allMatch(n -> n == 0)) {
      }
      
      if (IntStream.range(0, size).map(n -> array[n][size-n-1]).allMatch(n -> n == 1)) {
      }
      

      【讨论】:

        【解决方案3】:

        错误可能来自这样一个事实,即您在 row

        要检查次对角线,请尝试类似的方法:

        int maxIndex = array.length - 1;
        for(row = 0; row < maxIndex; row++){
          majDiag = row;
          if(array[row][maxIndex - row] != array[row+1][maxIndex - (row+1)]){
            isMatching = false;
            break;
          }
        }
        

        【讨论】:

          【解决方案4】:

          关于你的方法checkMajorDiagonal的几点:

          int majDiag;
          boolean isMatching = true;
          int row = 0;
          for(row = 0; row < array.length; row++){
              majDiag = row;   //not being used anywhere
              if(array[row][row] != array[row+1][row+1]){ //out of bounds with row+1
                  isMatching = false;
                  break;
              }
          }
          

          您可以删除未使用的majDiag变量并将循环代码更改为

          for(row = 0; row < array.length-1; row++)
          

          小对角逻辑:

          for(row = 0; row < array.length; row++){
            for(col = 0; col < array[i].length; col++){
                   if(row+col==array[i].length){
                           array[row][col] // this would be your minor diagonal element row wise
            }
          }
          

          【讨论】:

          • 谢谢。虽然我将如何开始使用小对角线?
          • 添加到答案
          • 请注意,我对小对角线的解决方案(上图)肯定更有效(O(n) 而不是 O(n squared))。但是,对于这种情况,它可能无关紧要。
          【解决方案5】:
           int diagonalValue = 0;
           for(int i = 0; i < 8 ; i++){
              diagonalValue  = array[i][j];
            for(int j = 0; j < 8 ; j++)
                if(i==j){
                    if(array[i][j]==diagonalValue){
                      counter++;  
                      } 
                    else 
                        break;
                   }
            }
          }
          if(counter==8) // yes they are same else not
          

          保持数组的大小,即变量中的 9 以使其松散耦合。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-28
            • 1970-01-01
            • 2020-07-24
            • 2016-12-21
            • 1970-01-01
            • 2020-03-19
            • 1970-01-01
            • 2014-11-13
            相关资源
            最近更新 更多