#include <iostream>
#include <fstream>
using namespace std;
fstream file;
class sparse_matrix {
const static int MAX = 32;
public:
int** data;
int row, col;
int len = 0;
sparse_matrix(int r, int c) {
row = r;
col = c;
data = new int* [MAX];
for (int i = 0; i < MAX; i++)
data[i] = new int[3];
data[len][0] = r;
data[len][1] = c;
data[len][2] = len;
len++;
}
-----------------------------------------------
void insert(int r, int c, int val) {
if (r > row || c > col) {
cout << "Wrong entry";
return;
}
else {
data[len][0] = r;
data[len][1] = c;
data[len][2] = val;
data[0][2] = len;
len++;
}
}
void void1(int row, int col, int arr[][12]) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (arr[i][j] != 0) {
insert(i, j, arr[i][j]);
}
}
}
}
-----------------------------------------------
void threeCol_plus(sparse_matrix a, sparse_matrix b) {
int i, j;
for (i = 1, j = 1;i < a.len && j < b.len;) {
int pos_a = a.data[i][0] * a.data[0][1] + a.data[i][1];
int pos_b = b.data[j][0] * b.data[0][1] + b.data[j][1];
if (pos_a < pos_b) {
insert(a.data[i][0], a.data[i][1], a.data[i][2]);
i++;
}
else if (pos_a > pos_b) {
insert(b.data[j][0], b.data[j][1], b.data[j][2]);
j++;
}
else if (pos_a == pos_b) {
if (a.data[i][2] + b.data[j][2] != 0) {
insert(a.data[i][0], a.data[i][1], a.data[i][2] + b.data[j][2]);
}
i++;
j++;
}
}
while (i < a.len) {
insert(a.data[i][0], a.data[i][1], a.data[i][2]);
i++;
}
while (j < b.len) {
insert(b.data[j][0], b.data[j][1], b.data[j][2]);
j++;
}
}
void print()
{
cout << "Dimension: " << row << "x" << col;
cout << "\nSparse Matrix: \n\tRow\tColumn\tValue\n";
for (int i = 0; i < len; i++)
{
cout << i << "\t" << data[i][0] << "\t " << data[i][1]
<< "\t " << data[i][2] << endl;
if (i == 0)
cout << endl;
}
cout << endl;
}
};
int main()
{
file.open("sparse_matrix.txt");
int a[10][12], b[10][12];
char judge;
if (!file) {
cout << "Failed to open file.\n";
system("PAUSE");
exit(1);
}
else {
if (file >> judge, judge != 'A')
exit(1);
for (int i = 0; i < 10; i++)
for (int j = 0; j < 12; j++)
file >> a[i][j];
if (file >> judge, judge != 'B')
exit(1);
for (int i = 0; i < 10; i++)
for (int j = 0; j < 12; j++)
file >> b[i][j];
}
sparse_matrix sparse_a(10, 12);
sparse_a.void_1(sparse_a.row, sparse_a.col, a);
cout << "Sparse Martix A:" << endl;
sparse_a.print();
sparse_matrix sparse_b(10, 12);
sparse_b.void_1(sparse_b.row, sparse_b.col, b);
cout << "Sparse Martix B:" << endl;
sparse_b.print();
sparse_matrix sparse_a_plus_b(sparse_a.row, sparse_a.col);
sparse_a_plus_b.threeCol_plus(sparse_a, sparse_b);
cout << "Sparse Martix A+B:" << endl;
sparse_a_plus_b.print();
}