Determine if a given Matrix is a Sparse Matrix in Java



Note: In numerical analysis, a sparse matrix is amatrix in which most of the elements are zero. By contrast, if most of the elements are nonzero, then the matrix is considered dense. The fraction of zero elements over the total number of elements in a matrix is called the sparsity (density).

public class SparceMatrix {

    public static void main(String args[]) {
        int a[][] = new int[3][3];
        int count=0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter element of Matrix ");
        for (int i = 0; i <= 2; i++) 
        {
            for (int j = 0; j <= 2; j++) 
            {
                a[i][j] = sc.nextInt();
            }
        }
        System.out.println("Value of Matrix is ");
        for (int i = 0; i <= 2; i++)
        {
            for (int j = 0; j <= 2; j++) 
            {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }

        for (int i = 0; i <= 2; i++) 

        {
            for (int j = 0; j <= 2; j++) 
            {
                if(a[i][j]==0)
                {
                count++;
                }
            }
        }

        if (count>((3*3)/2)) 

        {
            System.out.println("Given Matrix is Sparce Matrix");
        } else 
        {
            System.out.println("Given Matrix is not Sparce Matrix");
        }
    }
}


Output: 


(First Run..)


Enter element of Matrix 

1
0
2
0
0
3
4
0
0

Value of Matrix is 

1 0 2 
0 0 3 
4 0 0 

Given Matrix is Sparce Matrix .


(Second Run)


Enter element of Matrix 

1
2
0
0
5
5
0
4
4

Value of Matrix is 

1 2 0 
0 5 5 
0 4 4 

Given Matrix is not Sparce Matrix 



BUILD SUCCESSFUL (total time: 10 seconds)




No comments:

Post a Comment