#include
#include
#include
// Constants
const int MAX_ROWS = 20;
const int MAX_COLS = 20;
// Definition for a Matrix class
class Matrix {
private:
int matrix[MAX_ROWS][MAX_COLS];
int rows;
int cols;
void Change_Matrix (const int src_mat[MAX_ROWS][MAX_COLS], int dest_mat[MAX_ROWS][MAX_COLS], int rs, int cs, int row, int col);
int Determinant (const int array[MAX_ROWS][MAX_COLS], int rows, int cols);
int pow (int num, int n);
public:
Matrix () {rows = 0; cols = 0;}
Matrix (int r, int c) {rows = r; cols = c;}
void Print ();
void Set_Value (int row, int col, int num) {matrix[row][col] = num;}
void Set_Rows (int r) {rows = r;}
void Set_Cols (int c) {cols = c;}
int Get_Value (int row, int col) {return matrix[row][col];}
int Get_Rows () {return rows;}
int Get_Cols () {return cols;}
int Get_Determinant() {return Determinant (matrix, rows, cols);}
};
// Function changes a matrix in that way
// that it deletes row row and colon col fr
// om it and stores the result in dest_mat
void Matrix::Change_Matrix(const int src_mat[MAX_ROWS][MAX_COLS], int dest_mat[MAX_ROWS][MAX_COLS], int rs, int cs, int row, int col)
{
int new_x = 0;
int new_y = 0;
for (int x = 0; x < rs; x++) {
for (int y = 0; y < cs; y++) {
if ((x != row) && (y != col)) {
dest_mat[new_x][new_y] = src_mat[x][y];
new_y++;
if (new_y == cs - 1) {
new_y = 0;
new_x++;
}
}
}
}
}
// computes num to the nth power
int Matrix::pow (int num, int n)
{
int temp = num;
for (int x = 1; x < n; x++)
temp = temp * num;
return temp;
}
// prints out a matrix in a #nice# way
void Matrix::Print()
{
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
cout << setw(4) << matrix[x][y];
if (y == cols - 1) cout << endl;
}
}
}
// Recursive function that computes dete
// rminant of a matrix
int Matrix::Determinant (const int array[MAX_ROWS][MAX_COLS], int rows, int cols)
{
int dest[MAX_ROWS][MAX_COLS];
int temp = 0;
if (rows == 2) return ((array[0][0] * array[1][1])-(array[0][1] * array[1][0]));
for (int x = 0; x < cols; x++) {
Change_Matrix (array, dest, rows, cols, 0, x);
temp = temp + (pow(-1, x + 2) * array[0][x] * Determinant (dest, rows - 1, cols - 1));
}
return temp;
}
// End of class Matrix definition
//--------------------------------------
// ----------------------------------------
// --------------------------
//--------------------------------------
// ----------------------------------------
// --------------------------
void main()
{
// Declares a 5 x 5 matrix
Matrix m1 (4, 4);
int num = 1;
for (int x = 0; x < m1.Get_Rows(); x++) {
for (int y = 0; y < m1.Get_Cols(); y++) {
m1.Set_Value (x, y, num++);
}
}
cout << "Compute determinant - please wait...\n\n";
cout << "The determinant is: " << m1.Get_Determinant();
cout << "\n-----------------------\n";
m1.Print ();
getch();
}