Skip to content

Commit a859555

Browse files
committed
refactor(matrix): Improve code readability and error handling in determinant calculation
1 parent f93a562 commit a859555

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

src/main/java/com/thealgorithms/matrix/MatrixDeterminant.java

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
package com.thealgorithms.matrix;
2222

2323
public class MatrixDeterminant {
24+
private MatrixDeterminant() {
25+
throw new AssertionError("Utility class");
26+
}
2427

2528
public static double determinant(double[][] m) {
2629
int n = m.length;
@@ -29,29 +32,43 @@ public static double determinant(double[][] m) {
2932
throw new IllegalArgumentException("Matrix must be square");
3033
}
3134
}
32-
if (n == 1) return m[0][0];
33-
if (n == 2) return m[0][0]*m[1][1] - m[0][1]*m[1][0];
35+
if (n == 1) {
36+
return m[0][0];
37+
}
38+
39+
if (n == 2) {
40+
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
41+
}
3442

3543
double det = 0;
3644
for (int c = 0; c < n; c++) {
3745
det += Math.pow(-1, c) * m[0][c] * determinant(minor(m, 0, c));
3846
}
47+
3948
return det;
4049
}
4150

4251
private static double[][] minor(double[][] m, int row, int col) {
4352
int n = m.length;
44-
double[][] min = new double[n-1][n-1];
53+
double[][] min = new double[n - 1][n - 1];
4554
int r = 0;
4655
for (int i = 0; i < n; i++) {
47-
if (i == row) continue;
56+
if (i == row) {
57+
continue;
58+
}
59+
4860
int c = 0;
4961
for (int j = 0; j < n; j++) {
50-
if (j == col) continue;
62+
if (j == col) {
63+
continue;
64+
}
65+
5166
min[r][c++] = m[i][j];
5267
}
68+
5369
r++;
5470
}
71+
5572
return min;
5673
}
5774
}

src/test/java/com/thealgorithms/matrix/MatrixDeterminantTest.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
package com.thealgorithms.matrix;
22

33
import org.junit.jupiter.api.Test;
4-
import static org.junit.jupiter.api.Assertions.*;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
56

67
class MatrixDeterminantTest {
78

0 commit comments

Comments
 (0)