Write a program to declare a square matrix M[][] of order ‘N’. Check if the matrix is a Doubly Markov matrix or not. A matrix which satisfies the following conditions is Doubly Markov Matrix:
(i) All elements are >= 0
(ii) Sum of each row = 1
(iii) Sum of each column = 1
Accept ‘N’ from the user where 3 <= N <= 9. Display an appropriate error message if ‘N’ is not in the given range or the entered numbers are negative. Allow the user to create a matrix and check whether the created matrix is a Doubly Markov Matrix or not.
Test your program for the following data and some random data:
Example 1
INPUT: N = 3
Enter elements in the matrix: 0.5, 0.25, 0.25, 0.25, 0.75, 0.0, 0.25, 0.0, 0.75
OUTPUT: FORMED MATRIX
0.5 | 0.25 | 0.25 |
0.25 | 0.75 | 0.0 |
0.25 | 0.0 | 0.75 |
IT IS A DOUBLY MARKOV MATRIX
Example 2
INPUT: N = 3
Enter elements in the matrix: 1.5, 3, 0.15, 0.25, 4, 1.0, 0.25, 1.0, 3
OUTPUT: FORMED MATRIX
1.5 | 3 | 0.15 |
0.25 | 4 | 1.0 |
0.25 | 1.0 | 3 |
IT IS NOT A DOUBLY MARKOV MATRIX
Example 3
INPUT: N = 3
Enter elements in the matrix: 0.8, -4.0, 0.9, 3.5, 0.25, 0.25, 0.5, 0.0, 0.5
OUTPUT: NEGATIVE NUMBERS ENTERED. INVALID ENTRY
Example 4
INPUT: N = 12
OUTPUT: SIZE IS OUT OF RANGE. INVALID ENTRY
import java.util.Scanner;
class DoublyMarkov{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(n < 3 || n > 9){
System.out.println("SIZE IS OUT OF RANGE. INVALID ENTRY");
return;
}
double m[][] = new double[n][n];
boolean isNegative = false;
System.out.println("Enter elements in the matrix:");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
m[i][j] = Double.parseDouble(in.nextLine());
if(m[i][j] < 0)
isNegative = true;
}
}
if(isNegative){
System.out.println("NEGATIVE NUMBERS ENTERED. INVALID ENTRY");
return;
}
System.out.println("FORMED MATRIX");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++)
System.out.print(m[i][j] + "\t");
System.out.println();
}
boolean isMarkov = true;
for(int i = 0; i < n; i++){
double rowSum = 0.0;
double colSum = 0.0;
for(int j = 0; j < n; j++){
rowSum += m[i][j];
colSum += m[j][i];
}
if(rowSum != 1)
isMarkov = false;
if(colSum != 1)
isMarkov = false;
}
if(isMarkov)
System.out.println("IT IS A DOUBLY MARKOV MATRIX");
else
System.out.println("IT IS NOT A DOUBLY MARKOV MATRIX");
}
}