Lecture Notes on 27 July 2016 public class Array2D { // determines if a square 2-D array is magic public static boolean isMagic (int[][] a) { int dim = a.length; int canon_sum = dim * (1 + dim * dim) / 2; // sum the rows of a and see if they are equal to the canon_sum for (int i = 0; i < a.length; i++) { int sum = 0; for (int j = 0; j < a[i].length; j++) { sum += a[i][j]; } if (sum != canon_sum) return false; } // sum the columns and check if they are equal to the canon_sum for (int j = 0; j < a[0].length; j++) { int sum = 0; for (int i = 0; i < a.length;i++) { sum += a[i][j]; } if (sum != canon_sum) return false; } // sum the LR diagonal of a and check int sumLR = 0; for (int i = 0; i < a.length; i++) { sumLR += a[i][i]; } if (sumLR != canon_sum) return false; // sum the RL diagonal of a and check int sumRL = 0; for (int i = 0; i < a.length; i++) { sumRL += a[i][a.length - 1 - i]; } if (sumRL != canon_sum) return false; // passed all the tests return true; } public static int[][] transpose (int[][] a) { int[][] b = new int [a[0].length][a.length]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { b[j][i] = a[i][j]; } } return b; } public static int[][] matrixAdd (int[][] a, int[][] b) { int[][] c = new int [a.length][a[0].length]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { c[i][j] = a[i][j] + b[i][j]; } } return c; } public static void copyArray (int[][] a, int[][] b) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { b[i][j] = a[i][j]; } } } public static void fillArray (int[][] a, int x) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { a[i][j] = x; } } } public static void main (String[] args) { int[][] a = new int [10][10]; fillArray (a, -1); int[][] b = new int [a.length] [a[0].length]; copyArray (a, b); } }