/* Add Sparse Matrix...- Contributed by Tushar Anand */
#include<stdio.h>
#include<stdlib.h>
struct sparse
{
int *arr;
int cnt;
};
int c=0;
void create(struct sparse *s)
{
int arr[3][3];
int l,i,j;
s->cnt=0;
printf("Enter elements\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
if(arr[i][j]!=0)
s->cnt++;
}//for j
}//for i
if(s->cnt>9/2)
{
printf("\nNot Sparse matrix\n");
}
else
{
c=1;
s->arr=(int *)malloc(sizeof(int)*(s->cnt+1)*3);
*(s->arr+0)=3;
*(s->arr+1)=3;
*(s->arr+2)=s->cnt;
l=3;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(arr[i][j]!=0)
{
*(s->arr+l+0)=i;
*(s->arr+l+1)=j;
*(s->arr+l+2)=arr[i][j];
l=l+3;
}//if
}//for j
}//for i
}
}
display(struct sparse *s)
{
int i;
for(i=0;i<(s->cnt)*3+3;i++)
{
if(i%3==0&&i!=0)
printf("\n");
printf("%d\t",*(s->arr+i));
}//for i
}
void add(struct sparse *s1,struct sparse *s2,struct sparse *s3)
{
int i,j,k=3,l=3,m=3,flag=0;
s3->arr=(int *)malloc(sizeof(int)*(s1->cnt+s2->cnt+1)*3);
*(s3->arr+0)=3;
*(s3->arr+1)=3;
for(i=0;i<3;i++)
{
if(*(s1->arr+m+0)==i &&*(s2->arr+l+0)==i)
{
for(j=0;j<3;j++)
{
if(*(s1->arr+m+1)==j&&*(s2->arr+l+1)==j && *(s1->arr+m+0)==i &&*(s2->arr+l+0)==i)
{
*(s3->arr+k+0)=i;
*(s3->arr+k+1)=j;
*(s3->arr+k+2)=*(s1->arr+m+2)+*(s2->arr+l+2);
k+=3;
flag++;
m+=3;
l+=3;
}
else if(*(s1->arr+m+1)==j && *(s1->arr+m+0)==i)
{
*(s3->arr+k+0)=i;
*(s3->arr+k+1)=j;
*(s3->arr+k+2)=*(s1->arr+m+2);
flag++;
k+=3;
m+=3;
}
else if(*(s2->arr+l+1)==j && *(s2->arr+l+0)==i)
{
*(s3->arr+k+0)=i;
*(s3->arr+k+1)=j;
*(s3->arr+k+2)=*(s2->arr+l+2);
flag++;
k+=3;
l+=3;
}
}
}
else if(*(s1->arr+m+0)==i)
{
for(j=0;j<3;j++)
{
*(s3->arr+k+0)=i;
*(s3->arr+k+1)=j;
*(s3->arr+k+2)=*(s1->arr+m+2);
flag++;
k+=3;
m+=3;
}
}
else if(*(s2->arr+l+0)==i)
{
for(j=0;j<3;j++)
{
*(s3->arr+k+0)=i;
*(s3->arr+k+1)=j;
*(s3->arr+k+2)=*(s2->arr+l+2);
flag++;
k+=3;
l+=3;
}
}
}
*(s3->arr+2)=flag;
s3->cnt=flag;
}
void main()
{
struct sparse head,head1,head2;
create(&head);
create(&head1);
if(c==1)
{
display(&head);
display(&head1);
add(&head,&head1,&head2);
printf("\n\nAdded matrix :: \n\n");
display(&head2);
}
}
No comments:
Post a Comment