Write a method called isIdentityMatrix which will take a two-dimensional integer
array as argument, and returns true if the array is an identity matrix, or false otherwise.
You may use the following header for this method:
static boolean isIdentityMatrix(int[][] array)
A matrix is an identity matrix if it is a square matrix, and all its elements at the left
diagonal are ones, and all other elements are zeroes.
For example, the following matrix is an identity matrix and the method should return true
if we pass it to the isIdentityMatrix matrix as two-dimensional:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
For the following two-dimensional array, the method should return false because there
are some non-zero elements in the matrix.
1 0 0 5 0
0 1 0 2 0
0 3 1 0 0
0 0 0 1 5
0 5 0 0 1
Similarly, for the following two-dimensional array, the method should return false
because some elements at left diagonal are not ones.
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 1
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
int[][] array = { { 1, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 1, 0 },
{ 0, 0, 0, 0, 1 } };
if (isIdentityMatrix(array)) {
System.out.println("The array is an identity matrix");
} else {
System.out.println("The array is NOT an identity matrix");
}
}
static boolean isIdentityMatrix(int[][] array) {
if (array == null || array.length != array[0].length) {
return false;
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if ((i != j && array[i][j] != 0) || (i == j && array[i][j] != 1)) {
return false;
}
}
}
return true;
}
}
Comments
Leave a comment