-
Notifications
You must be signed in to change notification settings - Fork 237
/
Matrix
128 lines (115 loc) · 2.61 KB
/
Matrix
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
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
void printsparse(int b[MAX][3]);
void readsparse(int b[MAX][3]);
void addsparse(int b1[MAX][3], int b2[MAX][3], int b3[MAX][3]);
void main()
{
int b1[MAX][3], b2[MAX][3], b3[MAX][3];
readsparse(b1);
readsparse(b2);
addsparse(b1, b2, b3);
printsparse(b3);
}
void readsparse(int b[MAX][3])
{
int i, t, m, n;
printf("\nEnter no.of rows and columns:");
scanf("%d %d", &m, &n);
printf("No.of non - zero triples: ");
scanf("%d", &t);
b[0][0] = m;
b[0][1] = n;
b[0][2] = t;
for (i = 1; i <= t; i++)
{
printf("Enter the triples(row, column, value) : ");
scanf("%d %d %d", &b[i][0], &b[i][1], &b[i][2]);
}
}
void addsparse(int b1[MAX][3], int b2[MAX][3], int b3[MAX][3])
{
int t1, t2, i, j, k;
if (b1[0][0] != b2[0][0] || b1[0][1] != b2[0][1])
{
printf("\nYou have entered invalid matrix !!Size must be equal");
exit(0);
}
t1 = b1[0][2];
t2 = b2[0][2];
i = j = k = 0;
b3[0][0] = b1[0][0];
b3[0][1] = b1[0][1];
while (i <= t1 && j <= t2)
{
if (b1[i][0] < b2[j][0])
{
b3[k][0] = b1[i][0];
b3[k][1] = b1[i][1];
b3[k][2] = b1[i][2];
k++;
i++;
}
else if (b2[j][0] < b1[i][0])
{
b3[k][0] = b2[j][0];
b3[k][1] = b2[j][1];
b3[k][2] = b2[j][2];
k++;
j++;
}
else if (b1[i][1] < b2[j][1])
{
b3[k][0] = b1[i][0];
b3[k][1] = b1[i][1];
b3[k][2] = b1[i][2];
k++;
i++;
}
else if (b2[j][1] < b1[i][1])
{
b3[k][0] = b2[j][0];
b3[k][1] = b2[j][1];
b3[k][2] = b2[j][2];
k++;
j++;
}
else
{
b3[k][0] = b1[i][0];
b3[k][1] = b1[i][1];
b3[k][2] = b1[i][2] + b2[j][2];
k++;
i++;
j++;
}
}
while (i <= t1)
{
b3[k][0] = b1[i][0];
b3[k][1] = b1[i][1];
b3[k][2] = b1[i][2];
i++;
k++;
}
while (j <= t2)
{
b3[k][0] = b2[j][0];
b3[k][1] = b1[j][1];
b3[k][2] = b1[j][2];
j++;
k++;
}
b3[0][2] = k - 1;
}
void printsparse(int b[MAX][3])
{
int i, t;
t = b[0][2];
printf("\nrowtcolumntvalue");
for (i = 1; i <= t; i++)
{
printf("\n %d\t %d\t %d", b[i][0], b[i][1], b[i][2]);
}
}