Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <conio.h>
/*
compressed_sparse_matrix in cpp
author: Morteza Zakeri
date: 2012-10-23
*/
using namespace std;
//*************************************
void printArray(int **A, int row, int column)
{
for(int i=0; i<row; i++){
for(int j=0; j<column; j++){
cout << "A[" << i << "][" << j << "] = ";
cout << A[i][j];
cout << endl;
}
}
cout<<"\nPress any key ... ";
_getch();
}
//*************************************
int** buildread_SparseArray(int row, int column)
{
//Build dynamic 2D array(dynamic matrix):
int**A = new int*[row];
for(int i=0; i<row; i++)
A[i]=new int[column];
//Scan data from keyboard and put them to array:
cout << "\nPut your data to array:\n";
for(int i=0; i<row; i++){
for(int j=0; j<column; j++){
cout << "A[" << i << "][" << j << "] = "; cin >> A[i][j];
}
}
return A;
}
//**************************************
int ** decreaseSparseArray(int **A,int row,int column)
{
//Calcute number of unzero members of sparse array:
int newrow = 1, newcolumn = 3;
for(int i=0; i<row; i++)
for(int j=0; j<column; j++)
if(A[i][j] != 0)
newrow++;
//Build new decreased array:
int**C = new int*[newrow];
for(int i=0; i<newrow; i++)
C[i] = new int[newcolumn];
//Fill the first row of new array:
int rowindex = 0, columnindex = 0;
C[rowindex][0] = row;
C[rowindex][columnindex + 1] = column;
C[rowindex][columnindex + 2] = newrow-1;
rowindex++;
//Put unzero members of sparse array to new array:
for(int i=0; i<row; i++){
for(int j=0; j<column; j++){
if(A[i][j] != 0){
C[rowindex][columnindex] = i;
C[rowindex][columnindex + 1] = j;
C[rowindex][columnindex + 2] = A[i][j];
rowindex++;}
}
}
//Print array:
printArray(C, newrow, newcolumn);
return C;
}
//**************************************
int main()
{
//Define array sizes:
int prow, pcolumn;
cout << "Enter size of your array:\n::Row = "; cin >> prow;
cout << "::column = "; cin >> pcolumn;
cout << "\n-------------------- Sparse Array is : ----------------------\n";
int** B = buildread_SparseArray(prow, pcolumn);
cout << "\n-------------------- Decrease Array is : ----------------------\n";
int** C = decreaseSparseArray(B, prow,pcolumn);
//_getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment