Advertisement
elirang

calculate & compare slash diagonals in square matrix

Apr 16th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. class alaxon {
  2.     public static boolean calc_slash_diagonal(int[][] sqr) { // calc by right and down
  3.         // # right through the first row
  4.         int i=0;
  5.         int ret = calc_slash_diagonal(sqr, 0, i, 0);
  6.         i++;
  7.         while (i <= sqr.length-1) {
  8.             if (ret == calc_slash_diagonal(sqr, 0, i, 0))
  9.                 i++;
  10.             else
  11.                 return false;
  12.         }
  13.        
  14.         // # down through the last column from the second line
  15.             int j=1;
  16.         i = sqr.length-1;  
  17.         while (j <= sqr.length-1) {
  18.             if (ret == calc_slash_diagonal(sqr, j, i, 0))
  19.                 j++;
  20.             else
  21.                 return false;
  22.         }
  23.         return true;
  24.     }
  25.  
  26.     public static int calc_slash_diagonal(int[][] sqr, int x, int y, int sum) {
  27.         if ((x > sqr.length-1) || (x < 0) || (y > sqr.length-1 || (y < 0))) { // end of diagonal
  28.             return sum;
  29.         }
  30.         return calc_slash_diagonal(sqr, x+1, y-1, sum+sqr[x][y]);
  31.     }
  32.  
  33.     public static void main(String[] args) {
  34.         int[][] sqr = { {8, -3, 3, 1, 0},
  35.                     {11, 4, 3, 2, 8},
  36.                 {1, 6, 3, 0, 8},
  37.                 {-2, 2, 0, 7, 3},
  38.                 {1, 0, -7, 5, 8} };
  39.        
  40.         int[][] sqr2 = { {8, -3, 3, 1, 0},
  41.                     {11, 4, 3, 2, 8},
  42.                 {1, 6, 3, 0, 8},
  43.                 {-2, 2, 0, 7, 3},
  44.                 {1, 0, -7, 5, 9} };
  45.  
  46.  
  47.          int[][] sqr3 = { {8, 8, 8, 8, 8},
  48.                                 {0, 0, 0, 0, 8},
  49.                                 {0, 0, 0, 0, 8},
  50.                                 {0, 0, 0, 0, 7},
  51.                                 {0, 0, 0, 1, 8} };
  52.  
  53.                 System.out.println(calc_slash_diagonal(sqr));
  54.                 System.out.println(calc_slash_diagonal(sqr2));
  55.                 System.out.println(calc_slash_diagonal(sqr3));
  56.  
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement