Tuesday, 1 August 2017

Matrix into its sparse representation in c

#include <stdio.h>
#include <stdlib.h>
struct element{
    int row,col,value;
}*sparse;
int main()
{
    int n,m,i,j,c=0;
    // here n is row and m is column of matrix.
    // c represents number of non zero elements.
    int **A;
    printf("Enter the value of n\n");
    scanf("%d",&n);
    printf("Enter the value of m\n");
    scanf("%d",&m);
    A = (int**) malloc(n*sizeof(int*));
    for(i=0;i<n;i++){
            A[i] = (int*) malloc(m*sizeof(int));
    }
    printf("Enter the elements of the matrix\n");
    for(i=0;i<n;i++){
             for(j=0;j<m;j++){
                scanf("%d",&A[i][j]);
                if(A[i][j]!=0){
                    c++;
                }
             }
    }
    printf("Entered Matrix is :\n");
    for(i=0;i<n;i++){
             for(j=0;j<m;j++){
                 printf("%d ",A[i][j]);
             }
    printf("\n");
    }
    printf("Number of non zero elements is :%d\n",c);

    if((c+1)*3 <(n*m)){

            sparse = (struct element*) malloc(sizeof(struct element)*(c+1));
            int k=0;
            sparse[k].row = n;
            sparse[k].col = m;
            sparse[k].value = c;
            k=k+1;
            for(i=0;i<n;i++){
                for(j=0;j<m;j++){
                    if(A[i][j]!=0){
                        sparse[k].row = i;
                        sparse[k].col = j;
                        sparse[k].value= A[i][j];
                        k++;
                    }
                }
            }
            printf("Sparse representation of your matrix is\n");
            for(k=0;k<c+1;k++){
                printf("%d %d %d\n",sparse[k].row,sparse[k].col,sparse[k].value);
            }

    }
    else{
        printf("Sparse representation is not efficient\n");
    }
    // Don't forget to free the matrix.

    for(i=0;i<n;i++){
        free(A[i]);

    }
    free(A);
}

All In One Blog

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.

0 comments:

Post a Comment

 

Copyright @ 2015