2017-03-07 57 views
-3

我正在處理任何大小的正方形網格(3x3,4x4等)的雙數組我想創建一個布爾方法來檢查每行,列和對角線的總和彼此相等。如果所有的和都相等,那麼該方法返回布爾值true。 迭代網格並比較所有和的最佳方式是什麼?比較表中的總和

//check sum of diagonal 
    int sum = 0; 
    for (int ix = 0; ix < arr.length; ++ix) 
    { 
     sum =+ arr[ix][ix]; 
    } 

    //sum rows 

     for (int row = 0; row < arr.length; ++row) 
     { 
      for (int col = 0; col < arr[row].length; ++col) 
      { 
       sumRow =+ arr[row][col]; 
       if(sumRow == sum) 
       { 
        for (row = 0; row < arr.length; ++row) 
        { 
         for (col = 0; col < arr[row].length; ++col) 
         { 
          sumRow =+ arr[row][col]; 
         } 
        } 
       } 
       else 
       { 
        return bln; 
       } 
      } 
     } 


    if (sumRow == sum) 
    { 
     for (int col = 0; col < arr[0].length; ++col) 
     { 
      for (int row = 0; row < arr.length; ++row) 
      { 
       sumCol =+ arr[row][col]; 
      } 
     } 
    } 


    if (sumRow == sum && sumCol == sum) 
    { 
     bln = true; 
    } 
    else 
    { 
     return bln; 
    } 
    return bln; 
} 
+2

到目前爲止你做了什麼? – nullpointer

+0

你有這麼多的3x3,4x4矩陣嗎? – smttsp

+0

我知道這是不正確的,我只是不知道如何更準確地做到這一點 – shev

回答

1

我不會實現完整的解決方案,但因爲你是在正確的軌道上的方法vaildSquareMatrix意見正式確定你自己的想法。

import java.util.Arrays; 

class Main { 
    public static void main(String[] args) { 
    //two matrices for testing (Your can create bigger test matrices if you want) 
    int matrix1[][] = {{5,5,5},{5,5,5},{5,5,5}}; 
    int matrix2[][] = {{5,4,3},{2,3,5},{3,2,4}}; 
    System.out.println(validSquareMatrix(matrix1)); // should return true 
    System.out.println(validSquareMatrix(matrix2)); // should return false 
    } 

    public static boolean validSquareMatrix(int matrix[][]) { 
    //System.out.println(Arrays.deepToString(matrix)); // useful for debugging 

    int sum = 0; 

    //TODO: store the value for the total of the first row in sum 

    //TODO: check all other rows to see if the total of each row equals sum, return false if a row's total does not 

    //TODO: check all columns totals see if the total of each column equals sum, return false if a columns's total does not 

    //TODO: check both diagonals total to see if they both equal sum, return false if either diagonals total does not 

    //else return true 
    return true; 
    } 
}