TheAlgorithms-C-Plus-Plus/others/sparse_matrix.cpp

49 lines
1.2 KiB
C++
Raw Normal View History

/** @file
* A sparse matrix is a matrix which has number of zeroes greater than
2020-05-29 02:25:00 +08:00
* \f$\frac{m\times n}{2}\f$, where m and n are the dimensions of the matrix.
*/
2017-12-24 01:30:49 +08:00
#include <iostream>
2018-03-27 23:51:33 +08:00
2020-05-29 02:25:00 +08:00
/** main function */
int main() {
int m, n;
int counterZeros = 0;
std::cout << "Enter dimensions of matrix (seperated with space): ";
std::cin >> m;
std::cin >> n;
2020-05-26 21:37:36 +08:00
int **a = new int *[m];
for (int i = 0; i < m; i++) a[i] = new int[n];
std::cout << "Enter matrix elements:";
std::cout << "\n";
2018-03-27 23:51:33 +08:00
// reads the matrix from stdin
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
std::cout << "element? ";
std::cin >> a[i][j];
}
2018-03-27 23:51:33 +08:00
}
// counts the zero's
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
2020-05-29 02:25:00 +08:00
if (a[i][j] == 0)
counterZeros++; // Counting number of zeroes
}
2017-12-24 01:30:49 +08:00
}
2018-03-27 23:51:33 +08:00
// makes sure the matrix is a sparse matrix
if (counterZeros > ((m * n) / 2)) // Checking for sparse matrix
std::cout << "Sparse matrix";
else
std::cout << "Not a sparse matrix";
2020-05-26 21:37:36 +08:00
for (int i = 0; i < m; i++) delete[] a[i];
delete[] a;
return 0;
2017-12-24 01:30:49 +08:00
}