In: Computer Science
In java run through eclipse
/**
*
* Given a square array, determines if it is
diagonal
* That is, returns true if all values in the array are
0
* except the main diagonal. The main diagonal is
entries of the form
* data[i][j] where i == j. Elements on the main
* diagonal can be 0 or any other number.
*
* Examples:
* {{1,0,0},
* {0,2,0}
* {0,0,3}} yields true
*
* {{1,0,9},
* {0,2,0},
* {0,0,3}} yields false because 0,2 is nonzero
*
* {{0,0,0},
* {0,0,0},
* {0,0,3}} yields true because there can be 0
* entries on the diagonal if desired
* @param data input array
* @return true if it is diagonal, false
otherwise
*/
public static boolean isDiagonal(int[][] data) {
return false;
}
public class IsDiagonal {
/**
* Given a square array, determines if it is diagonal
* That is, returns true if all values in the array are 0
* except the main diagonal. The main diagonal is entries of the form
* data[i][j] where i == j. Elements on the main
* diagonal can be 0 or any other number.
* <p>
* Examples:
* {{1,0,0},
* {0,2,0}
* {0,0,3}} yields true
* <p>
* {{1,0,9},
* {0,2,0},
* {0,0,3}} yields false because 0,2 is nonzero
* <p>
* {{0,0,0},
* {0,0,0},
* {0,0,3}} yields true because there can be 0
* entries on the diagonal if desired
*
* @param data input array
* @return true if it is diagonal, false otherwise
*/
public static boolean isDiagonal(int[][] data) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (i != j && data[i][j] != 0) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
System.out.println(isDiagonal(new int[][]{{1, 0, 0}, {0, 2, 0}, {0, 0, 3}}));
System.out.println(isDiagonal(new int[][]{{1, 0, 9}, {0, 2, 0}, {0, 0, 3}}));
System.out.println(isDiagonal(new int[][]{{0, 0, 0}, {0, 0, 0}, {0, 0, 3}}));
}
}
