Program opened below. You can scroll through the algorithm, Java code and output.

Doubly Markov Matrix

Download .java

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).

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
import 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");
}
}
Input: 2 0.5 0.5 0.5 0.5 Output: DOUBLY MARKOV MATRIX
← Previous Program 77 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.