在2d阵列上添加对角线

时间:2016-12-01 02:51:51

标签: java

我有这个代码是由我的教授编写的,但我不完全理解对角线循环是如何工作的,我的工作是完成循环的行和列,所以我理解那里发生了什么。该数组就像一个表,就像这样:

 int [][] square = {
//colums 0   1  2   3
     //0{16, 3, 2, 13},
     //1{5, 10, 11, 8},
     //2{9, 6, 7, 12 },
     //3{4, 15, 14, 1}}; 

我不理解的部分是通过对角线计数的for循环,如果我想取第一个元素的值我会选择位置[0] [0],让我说我想选择值10 我会去[1] [1]等我只是不知道这是怎么回事:

 for (int i = 0; i < square.length; i++)
           {
              sum += square[i][i];
           }

选择所有对角线值,对不起,但这对我没有意义。有人可以解释一下。

public static void main(String[] args) {
    int [][] square = {
        {16, 3, 2, 13},
        {5, 10, 11, 8},
        {9, 6, 7, 12 },
        {4, 15, 14, 1}


      }; 
   System.out.println("Is magic square: " + magicSquare(square));   
 }
   private static boolean magicSquare(int[][] square){

   //calculate the sum of the first row and assign it to n
       int n = sumOfRow(square[0]);

       for (int[] row : square)
       {
          int sum = sumOfRow(row);        
          if (sum != n)
          return false;   
       }
       int sum = 0;

       //rows
      for (int i = 0; i < square.length; i++){
          sum = 0;
          for (int j = 0; j < square.length; j++){
              sum += square[i][j];
          }
          if(sum != n){
             return false;
          }
      }
       // columns

       for(int i =0; i < square.length; i++){
           sum = 0;

           for(int j = 0; j< square.length; j++){
               sum += square[j][i];
           }
           if(sum != n){
               return false;
           }
       }
       //diagonal from top left corner to bottom right corner
       sum = 0;
       for (int i = 0; i < square.length; i++)
       {
          sum += square[i][i];
       }
       if (sum != n)
          return false;

       sum = 0;
       // top right to bottom left diagonal
       for (int i = 0; i < square.length; i++)
       {
          sum += square[i][square.length - 1 - i];
       }
       if (sum != n)
          return false;
       return true;

    } 

   //returns the sum of the elements in the row
   private static int sumOfRow(int[] row){
      int sum = 0;
      for(int el : row){
         sum += el;
      }
      return sum;
   }

1 个答案:

答案 0 :(得分:3)

也许这会有所帮助。对于4 x 4阵列,您可以使用for循环中的值“展开”代替i的代码:

   //diagonal from top left corner to bottom right corner
   sum = 0;
   for (int i = 0; i < square.length; i++)
   {
      sum += square[i][i];
   }
   if (sum != n)
      return false;

   sum = 0;
   // top right to bottom left diagonal
   for (int i = 0; i < square.length; i++)
   {
      sum += square[i][square.length - 1 - i];
   }
   if (sum != n)
      return false;

会变成:

   sum = 0;
   sum += square[0][0];
   sum += square[1][1];
   sum += square[2][2];
   sum += square[3][3];
   if (sum != n)
      return false;

   sum = 0;
   sum += square[0][3];
   sum += square[1][2];
   sum += square[2][1];
   sum += square[3][0];
   if (sum != n)
      return false;

我希望这说清楚:它依次总结每个对角线并与目标值进行比较。