Tuesday, January 30, 2024

Sparse Matrix - DSTC using C Language (Source Code Implemented)

Sparse Matrix 
Implemented using C Language 
 Get Paid by Reading Ads on your Mobiles
 

C Language Code:

              SPARSE.H          

// DSTC ---- SPARSE.H .... sparse matrix ...header file
// it is matrix having only few elements as values and rest are zeros ...

#include<stdio.h>
#include<alloc.h>
#include<assert.h>

typedef struct s
{
int val;
int row,col;
struct s *up, *left ;
}node ;

typedef struct sparselist
{
node *arows;
node *acols;
int trows,tcols; // total no of rows and cols..
}sp ;
// prototype of the function ...
int output(sp *s,int r,int c) ;

sp *makesparse(int r,int c)
{
int i ;
sp *s1=(sp*)malloc(sizeof(sp));
s1->trows = r ;
s1->tcols = c;
s1->arows = (node *)malloc(sizeof(node)*r);
s1->acols = (node *)malloc(sizeof(node)*c);
for(i=0;i<s1->trows ; i++)
{
s1->arows[i].row = i ;
s1->arows[i].col = -1 ;
s1->arows[i].left = &s1->arows[i] ;
s1->arows[i].up = NULL ;
s1->arows[i].val = -1 ;
}
for(i=0;i<s1->tcols ; i++)
{
s1->acols[i].col = i ;
s1->acols[i].row = -1 ;
s1->acols[i].left = NULL ;
s1->acols[i].up = &s1->acols[i] ;
s1->acols[i].val = -1 ;
}
return (s1);
}

void addsparsenode(int r, int c, int v, sp* s)
{
node *n,*start;
assert(r>=0 && r<s->trows && c>=0 && c<s->tcols);
assert(v!=0) ;
n = (node *)malloc(sizeof(node));
n->val = v ;
n->row = r ;
n->col = c ;
start = &s->arows[r] ;
while(start->left->col > c)
start = start->left ;

if (start->left->col != c)
{
n->left = start->left ;
start->left = n ;
}

start = &s->acols[c] ;
while(start->up->row > r)
start = start->up ;

if (start->up->row != r)
{
n->up = start->up ;
start->up = n ;
}
}

void printsparse(sp *s)
{
int i,j ;
for(i=0;i<s->trows;i++)
{
printf("\n");
for(j=0;j < s->tcols; j++)
{
printf("\t %d",output(s,i,j));
}
}
}
int output(sp *s,int r,int c)
{
node *start= &s->arows[r] ;
while(start->left->col > c)
start=start->left ;

if (start->left->col == c)
return (start->left->val);
else
return 0;

}

       SPARSE.CPP       

// DSTC --- SPARSE.CPP --- sparse matrix ...
// using the file ... SPARSE.H

#include "sparse.h"
#include <stdlib.h>
#include <conio.h>

main()
{
sp *s1 = makesparse(3,3) ;
// addsparsenode(int r, int c, int v, sp* s)
clrscr();
addsparsenode(2,2,22,s1);
addsparsenode(2,1,21,s1);
addsparsenode(0,2,2,s1);
addsparsenode(1,1,11,s1);
printsparse(s1);
}

No comments: