Author: Sanif S S
Site: theeduzone.blogspot.com
Email: sanifss@gmail.com
#include<stdio.h>
#include<conio.h>
int m,n;
class sparse
{ int k,r,c,a[20][20],s[20][20],o[20][20];
public:
void read();
void display();
void convert();
void disparse();
void rescon(sparse);
void add(sparse,sparse);
};
void sparse::read()
{
for(int i=0;i
{
for(int j=0;j
{
cin>>a[i][j];
}
}
getch();
}
void sparse::display()
{
for(int i=0;i
{
for(int j=0;j
{
cout<
}
cout<<"\n";
}
}
void sparse::convert()
{ int i,j;
k=1;
for(i=0;i
{
for(j=0;j
{
if(a[i][j]!=0)
{
s[k][0]=i;
s[k][1]=j;
s[k][2]=a[i][j];
k++;
}
}
}
k--;
s[0][0]=m;
s[0][1]=n;
s[0][2]=k;
}
void sparse::disparse()
{
for(int i=0;i
{
for(int j=0;j<3;j++)
{
cout<
}
cout<<"\n";
}
getch();
}
void sparse::add(sparse s1,sparse s2)
{
int i=1,j=1;
k=1;
while((i<=s1.k)&&(j<=s2.k))
{
if(s1.s[i][0]
{
s[k][0]=s1.s[i][0];
s[k][1]=s1.s[i][1];
s[k][2]=s1.s[i][2];
k++;
i++;
}
else if(s1.s[i][0]>s2.s[j][0])
{
s[k][0]=s2.s[j][0];
s[k][1]=s2.s[j][1];
s[k][2]=s2.s[j][2];
k++;
j++;
}
else if(s1.s[i][1]
{
s[k][0]=s1.s[i][0];
s[k][1]=s1.s[i][1];
s[k][2]=s1.s[i][2];
i++;
k++;
}
else if(s1.s[i][1]>s2.s[j][1])
{
s[k][0]=s2.s[j][0];
s[k][1]=s2.s[j][1];
s[k][2]=s2.s[j][2];
k++;
j++;
}
else
{
s[k][0]=s1.s[i][0];
s[k][1]=s1.s[i][1];
s[k][2]=s1.s[i][2]+s2.s[j][2];
i++;
k++;
j++;
}
}
while(i<=s1.k)
{
s[k][0]=s1.s[i][0];
s[k][1]=s1.s[i][1];
s[k][2]=s1.s[i][2];
i++;
k++;
}
while(j<=s2.k)
{
s[k][0]=s2.s[j][0];
s[k][1]=s2.s[j][1];
s[k][2]=s2.s[j][2];
j++;
k++;
}
k--;
s[0][0]=m;
s[0][1]=n;
s[0][2]=k;
getch();
}
void sparse::rescon(sparse s3)
{
int i,j;
for(i=0;i
{for(j=0;j
{ o[i][j]=0;}
}
for(i=1;i
{
r=s3.s[i][0];
c=s3.s[i][1];
o[r][c]=s3.s[i][2];
}
cout<<"Converted resultant sparse matrix\n";
for(i=0;i
{for(j=0;j
{ cout<
}
cout<<"\n";
}
getch();
}
void main()
{ clrscr();
sparse s1,s2,s3,s4;
cout<<"Enter the order of matrix\n";
cin>>m>>n;
cout<<"Enter the first matrix\n";
s1.read();
cout<<"Enter the second matrix\n";
s2.read();
cout<<"First matrix is\n";
s1.display();
cout<<"Second matrix is\n";
s2.display();
s1.convert();
cout<<"The first sparse matrix is\n";
s1.disparse();
s2.convert();
cout<<"The second sparse matrix is\n";
s2.disparse();
s3.add(s1,s2);
cout<<"The sum sparse matrix is\n";
s3.disparse();
s4.rescon(s3);
getch();
}
No comments:
Post a Comment