-
Notifications
You must be signed in to change notification settings - Fork 7
/
sparse.cpp
92 lines (92 loc) · 1.71 KB
/
sparse.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include<stdlib.h>
struct Element
{
int i;
int j;
int x;
};
struct Sparse
{
int m;
int n;
int num;
struct Element *ele;
};
void create(struct Sparse *s)
{
int i;
printf("Eneter Dimensions");
scanf("%d%d",&s->m,&s->n);
printf("Number of non-zero");
scanf("%d",&s->num);
s->ele=(struct Element *)malloc(s->num*sizeof(struct
Element));
printf("Eneter non-zero Elements");
for(i=0;i<s->num;i++)
scanf("%d%d%d",&s->ele[i].i,&s->ele[i].j,&s->ele[i].x);
}
void display(struct Sparse s)
{
int i,j,k=0;
for(i=0;i<s.m;i++)
{
for(j=0;j<s.n;j++)
{
if(i==s.ele[k].i && j==s.ele[k].j)
printf("%d ",s.ele[k++].x);
else
printf("0 ");
}
printf("\n");
}
}
struct Sparse * add(struct Sparse *s1,struct Sparse *s2)
{
struct Sparse *sum;
int i,j,k;
i=j=k=0;
if(s1->n != s2->n && s1->m != s2->m)
return NULL;
sum=(struct Sparse *)malloc(sizeof(struct Sparse));
sum->ele=(struct Element *)malloc((s1->num+s2->num)*sizeof(struct Element));
while(i<s1->num && j<s2->num)
{
if(s1->ele[i].i<s2->ele[j].i)
sum->ele[k++]=s1->ele[i++];
else if(s1->ele[i].i>s2->ele[j].i)
sum->ele[k++]=s2->ele[j++];
else
{
if(s1->ele[i].j<s2->ele[j].j)
sum->ele[k++]=s1->ele[i++];
else if(s1->ele[i].j>s2->ele[j].j)
sum->ele[k++]=s2->ele[j++];
else
{
sum->ele[k]=s1->ele[i];
sum->ele[k++].x=s1->ele[i++].x+s2->ele[j++].x;
}
}
}
for(;i<s1->num;i++)sum->ele[k++]=s1->ele[i];
for(;j<s2->num;j++)sum->ele[k++]=s2->ele[j];
sum->m=s1->m;
sum->n=s1->n;
sum->num=k;
return sum;
}
int main()
{
struct Sparse s1,s2,*s3;
create(&s1);
create(&s2);
s3=add(&s1,&s2);
printf("First Matrix\n");
display(s1);
printf("Second Matrix\n");
display(s2);
printf("Sum Matrix\n");
display(*s3);
return 0;
}