Program opened below. You can scroll through the algorithm, Java code and output.
Program 77
Doubly Markov Matrix
Question
Accept a square matrix of real values. A matrix is doubly Markov when all elements are non-negative and every row and every column sums to 1 (allow a small rounding tolerance).
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input order N and reject invalid order.
Step 4: Input all N*N real values.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Check every element is non-negative.
Step 7: Calculate each row sum and each column sum.
Step 8: Each sum must be within 0.0001 of 1.
Step 9: Store the computed result and prepare it for display.
Step 10: If all checks pass, display DOUBLY MARKOV MATRIX; otherwise display NOT A DOUBLY MARKOV MATRIX.
Step 11: Stop.
Java program
Javaimport java.util.*;
class DoublyMarkov {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n < 1 || n > 9) {
System.out.println("INVALID ORDER");
return;
}
double[][] a = new double[n][n];
boolean ok = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextDouble();
if (a[i][j] < 0) {
ok = false;
}
}
}
for (int i = 0; i < n; i++) {
double row = 0, col = 0;
for (int j = 0; j < n; j++) {
row += a[i][j];
col += a[j][i];
}
if (Math.abs(row - 1.0) > 0.0001 || Math.abs(col - 1.0) > 0.0001) {
ok = false;
}
}
System.out.println(ok ? "DOUBLY MARKOV MATRIX" : "NOT A DOUBLY MARKOV MATRIX");
}
}Sample output
Input:
2
0.5 0.5
0.5 0.5
Output:
DOUBLY MARKOV MATRIX