Ad Code

Write a java program that accept conventional matrix and convert it into sparse matrix and print it.

 import java.util.Scanner;


public class SparseMatrixConverter {


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        // Accepting the conventional matrix

        System.out.println("Enter the number of rows in the matrix:");

        int rows = scanner.nextInt();


        System.out.println("Enter the number of columns in the matrix:");

        int cols = scanner.nextInt();


        int[][] conventionalMatrix = new int[rows][cols];


        System.out.println("Enter the elements of the matrix:");

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                conventionalMatrix[i][j] = scanner.nextInt();

            }

        }


        // Converting the conventional matrix to a sparse matrix

        int nonZeroCount = 0;

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                if (conventionalMatrix[i][j] != 0) {

                    nonZeroCount++;

                }

            }

        }


        int[][] sparseMatrix = new int[nonZeroCount + 1][3];

        sparseMatrix[0][0] = rows;

        sparseMatrix[0][1] = cols;

        sparseMatrix[0][2] = nonZeroCount;


        int sparseIndex = 1;

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                if (conventionalMatrix[i][j] != 0) {

                    sparseMatrix[sparseIndex][0] = i;

                    sparseMatrix[sparseIndex][1] = j;

                    sparseMatrix[sparseIndex][2] = conventionalMatrix[i][j];

                    sparseIndex++;

                }

            }

        }


        // Printing the sparse matrix

        System.out.println("Sparse Matrix:");

        for (int i = 0; i <= nonZeroCount; i++) {

            System.out.println(sparseMatrix[i][0] + " " + sparseMatrix[i][1] + " " + sparseMatrix[i][2]);

        }


        scanner.close();

    }

}


Reactions

Post a Comment

0 Comments