Skip to content

Commit f5405e8

Browse files
authored
Add MatrixDeterminant class to calculate determinants
Implement a function to calculate the determinant of a square matrix, handling singular matrices and non-square matrices.
1 parent 2da0465 commit f5405e8

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Problem: Determinant of a Matrix
2+
//
3+
// Implement a function to calculate the determinant of a square matrix.
4+
//
5+
// Requirements:
6+
// - The function should work for any n x n matrix.
7+
// - Return 0 if the matrix is singular (determinant = 0).
8+
// - Only square matrices are allowed; handle error for non-square matrices.
9+
//
10+
// Example:
11+
// double[][] matrix1 = {{1,2},{3,4}};
12+
// determinant(matrix1); // returns -2
13+
//
14+
// double[][] matrix2 = {{2,0,1},{3,0,0},{5,1,1}};
15+
// determinant(matrix2); // returns 3
16+
//
17+
// Notes:
18+
// - You can use recursion or any other suitable algorithm.
19+
// - Bonus: Optimize for larger matrices (optional).
20+
package matrix;
21+
22+
public class MatrixDeterminant {
23+
24+
public static double determinant(double[][] m) {
25+
int n = m.length;
26+
if (n == 1) return m[0][0];
27+
if (n == 2) return m[0][0]*m[1][1] - m[0][1]*m[1][0];
28+
29+
double det = 0;
30+
for (int c = 0; c < n; c++) {
31+
det += Math.pow(-1, c) * m[0][c] * determinant(minor(m, 0, c));
32+
}
33+
return det;
34+
}
35+
36+
private static double[][] minor(double[][] m, int row, int col) {
37+
int n = m.length;
38+
double[][] min = new double[n-1][n-1];
39+
int r = 0;
40+
for (int i = 0; i < n; i++) {
41+
if (i == row) continue;
42+
int c = 0;
43+
for (int j = 0; j < n; j++) {
44+
if (j == col) continue;
45+
min[r][c++] = m[i][j];
46+
}
47+
r++;
48+
}
49+
return min;
50+
}
51+
52+
public static void main(String[] args) {
53+
double[][] a = {{1,2},{3,4}};
54+
double[][] b = {{2,0,1},{3,0,0},{5,1,1}};
55+
System.out.println(determinant(a)); // -2
56+
System.out.println(determinant(b)); // 3
57+
}
58+
}

0 commit comments

Comments
 (0)