Skip to content

Commit 1e6f31c

Browse files
committed
refactor(matrix): Clean up code and improve formatting in MatrixDeterminant and its tests
1 parent a859555 commit 1e6f31c

File tree

2 files changed

+10
-40
lines changed

2 files changed

+10
-40
lines changed
Lines changed: 8 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,11 @@
1+
package com.thealgorithms.matrix;
2+
13
// 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).
204

21-
package com.thealgorithms.matrix;
5+
public final class MatrixDeterminant {
226

23-
public class MatrixDeterminant {
247
private MatrixDeterminant() {
25-
throw new AssertionError("Utility class");
8+
// Prevent instantiation
269
}
2710

2811
public static double determinant(double[][] m) {
@@ -32,19 +15,13 @@ public static double determinant(double[][] m) {
3215
throw new IllegalArgumentException("Matrix must be square");
3316
}
3417
}
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-
}
18+
if (n == 1) return m[0][0];
19+
if (n == 2) return m[0][0] * m[1][1] - m[0][1] * m[1][0];
4220

4321
double det = 0;
4422
for (int c = 0; c < n; c++) {
4523
det += Math.pow(-1, c) * m[0][c] * determinant(minor(m, 0, c));
4624
}
47-
4825
return det;
4926
}
5027

@@ -53,22 +30,14 @@ private static double[][] minor(double[][] m, int row, int col) {
5330
double[][] min = new double[n - 1][n - 1];
5431
int r = 0;
5532
for (int i = 0; i < n; i++) {
56-
if (i == row) {
57-
continue;
58-
}
59-
33+
if (i == row) continue;
6034
int c = 0;
6135
for (int j = 0; j < n; j++) {
62-
if (j == col) {
63-
continue;
64-
}
65-
36+
if (j == col) continue;
6637
min[r][c++] = m[i][j];
6738
}
68-
6939
r++;
7040
}
71-
7241
return min;
7342
}
7443
}

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

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

3-
import org.junit.jupiter.api.Test;
43
import static org.junit.jupiter.api.Assertions.assertEquals;
54
import static org.junit.jupiter.api.Assertions.assertThrows;
65

6+
import org.junit.jupiter.api.Test;
7+
78
class MatrixDeterminantTest {
89

910
@Test

0 commit comments

Comments
 (0)