-
Notifications
You must be signed in to change notification settings - Fork 0
/
sparse matrix add 2
120 lines (117 loc) · 3.1 KB
/
sparse matrix add 2
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <stdio.h>
void addition(int ktemp[3][100],int ltemp[3][100],int k,int l);
int main(){
int a[20][20],ktemp[3][100],n,m,p,q,count=0,i,j,k=0,b[20][20],l=0,ltemp[3][100];
printf("enter the row");
scanf("%d",&n);
printf("enter columns");
scanf("%d",&m);
for(i=0;i<n;i++){
for(j=0;j<m;j++){
printf("enter %d%d",i,j);
scanf("%d",&a[i][j]);
if(a[i][j]!=0){
ktemp[0][k]=i;
ktemp[1][k]=j;
ktemp[2][k]=a[i][j];
k++;
}
}
}
printf("sparse matrix is ");
for(i=0;i<3;i++){
for(j=0;j<k;j++){
printf("%d",ktemp[i][j]);
}
printf("\n");
}
printf("enter the row");
scanf("%d",&p);
printf("enter columns");
scanf("%d",&q);
if(p!=m||q!=n){
printf("addition can be performed on same order");
}
else{
for(i=0;i<n;i++){
for(j=0;j<m;j++){
printf("enter %d%d",i,j);
scanf("%d",&b[i][j]);
if(b[i][j]!=0){
ltemp[0][l]=i;
ltemp[1][l]=j;
ltemp[2][l]=b[i][j];
l++;
}
}
}
printf("sparse matrix is ");
for(i=0;i<3;i++){
for(j=0;j<l;j++){
printf("%d",ltemp[i][j]);
}
printf("\n");
}
addition(ktemp,ltemp,k,l);
}
}
void addition(int ktemp[3][100],int ltemp[3][100],int k,int l){
int i=0,j=0,sparse[3][100],x=0;
while(i<k&&j<l){
if((ktemp[0][i]==ltemp[0][j])&&(ltemp[1][j]==ktemp[1][i])){
printf("entered this ");
sparse[0][x]=ktemp[0][i];
sparse[1][x]=ktemp[1][i];
sparse[2][x]=ltemp[2][j]+ktemp[2][i];
x++;
i++;
j++;
}
else{
if(ktemp[0][i]<ltemp[0][j]){
sparse[0][x]=ktemp[0][i];
sparse[1][x]=ktemp[1][i];
sparse[2][x]=ktemp[2][i];
x++;
i++;
}
else{
if((ktemp[0][i]==ltemp[0][j])&&(ktemp[1][i]<ltemp[1][j])){
sparse[0][x]=ktemp[0][i];
sparse[1][x]=ktemp[1][i];
sparse[2][x]=ktemp[2][i];
x++;
i++;
}
else{
sparse[0][x]=ktemp[0][j];
sparse[1][x]=ktemp[1][j];
sparse[2][x]=ktemp[2][j];
x++;
j++;
}
}
}
}
while(i<k){
sparse[0][x]=ktemp[0][i];
sparse[1][x]=ktemp[1][i];
sparse[2][x]=ktemp[2][i];
x++;
i++;
}
while(j<l){
sparse[0][x]=ktemp[0][j];
sparse[1][x]=ktemp[1][j];
sparse[2][x]=ktemp[2][j];
x++;
j++;
}
printf("addition matrix is");
for(i=0;i<3;i++){
for(j=0;j<x;j++){
printf("%d",sparse[i][j]);
}
printf("\n");
}
}