diff --git a/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp new file mode 100644 index 00000000..786c5a76 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp @@ -0,0 +1,96 @@ +/*Description :c++ solution to check if a given matrix is sparse matrix. +If the count of zeroes present in the mmatrix is more than half the elements of the matrix, +it is flagged as a sparse matrix. +Also the tuple form of the matrix(if the said matrix is sparse) is displayed.*/ + + +#include +using namespace std; + +int compactMatrix(int sparseMatrix[4][5]) +{ + int size = 0; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 5; j++) + if (sparseMatrix[i][j] != 0) + size++; + + /* number of columns in compactMatrix (size) must be + equal to number of non - zero elements in sparseMatrix */ + int compactMatrix[size][3]; + + // Making of new matrix + int k = 0; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 5; j++) + if (sparseMatrix[i][j] != 0) + { + compactMatrix[k][0] = i; + compactMatrix[k][1] = j; + compactMatrix[k][2] = sparseMatrix[i][j]; + k++; + } + cout<<"The tuple form is:"< ((row * col)/ 2)) + { + cout<<"This is a sparse matrix"<