HomeLanguagesJavaJava Program for Markov matrix

Java Program for Markov matrix

Given a m x n 2D matrix, check if it is a Markov Matrix.
Markov Matrix : The matrix in which the sum of each row is equal to 1.
 

Example of Markov Matrix

Examples: 
 

Input :
1    0   0
0.5  0  0.5
0    0   1
Output : yes

Explanation :
Sum of each row results to 1, 
therefore it is a Markov Matrix.

Input :
1 0 0
0 0 2
1 0 0
Output :
no

 

Approach : Initialize a 2D array, then take another single dimensional array to store the sum of each rows of the matrix, and check whether all the sum stored in this 1D array is equal to 1, if yes then it is Markov matrix else not. 
 

Java




// Java code to check Markov Matrix
import java.io.*;
 
public class markov
{
    static boolean checkMarkov(double m[][])
    {
        // outer loop to access rows
        // and inner to access columns
        for (int i = 0; i < m.length; i++) {
 
            // Find sum of current row
            double sum = 0;
            for (int j = 0; j < m[i].length; j++)
                sum = sum + m[i][j];
 
            if (sum != 1)
               return false;
        }
 
        return true;
    }
 
    public static void main(String args[])
    {
        // Matrix to check
        double m[][] = { { 0, 0, 1 },
                         { 0.5, 0, 0.5 },
                         { 1, 0, 0 } };
 
        // calls the function check()
        if (checkMarkov(m))
            System.out.println(" yes ");
        else
            System.out.println(" no ");
    }
}


Output : 

yes

Time Complexity: O(M*N), Here M and N are the number of rows and columns respectively of a given matrix

Auxiliary Space: O(1)

Please refer complete article on Program for Markov matrix for more details!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32662 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7035 POSTS0 COMMENTS
Nicole Veronica
12173 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12260 POSTS0 COMMENTS
Shaida Kate Naidoo
7161 POSTS0 COMMENTS
Ted Musemwa
7427 POSTS0 COMMENTS
Thapelo Manthata
7124 POSTS0 COMMENTS
Umr Jansen
7127 POSTS0 COMMENTS