Skip to content

Commit d09a8ff

Browse files
committed
feat(matrix): Implement determinant calculation for square matrices
1 parent a4cf6e3 commit d09a8ff

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.thealgorithms.matrix;
2+
3+
// Problem: Determinant of a Matrix
4+
// Description: Calculate the determinant of any square matrix using recursion.
5+
// URL: https://en.wikipedia.org/wiki/Determinant
6+
7+
public final class MatrixDeterminant {
8+
9+
private MatrixDeterminant() {
10+
// Prevent instantiation
11+
}
12+
13+
public static double determinant(double[][] m) {
14+
int n = m.length;
15+
for (double[] row : m) {
16+
if (row.length != n) {
17+
throw new IllegalArgumentException("Matrix must be square");
18+
}
19+
}
20+
21+
if (n == 1) {
22+
return m[0][0];
23+
}
24+
25+
if (n == 2) {
26+
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
27+
}
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+
41+
for (int i = 0; i < n; i++) {
42+
if (i == row) {
43+
continue;
44+
}
45+
int c = 0;
46+
for (int j = 0; j < n; j++) {
47+
if (j == col) {
48+
continue;
49+
}
50+
min[r][c++] = m[i][j];
51+
}
52+
r++;
53+
}
54+
return min;
55+
}
56+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.matrix;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class MatrixDeterminantTest {
9+
10+
@Test
11+
void test2x2Matrix() {
12+
double[][] matrix = {{1, 2}, {3, 4}};
13+
assertEquals(-2, MatrixDeterminant.determinant(matrix), 1e-9);
14+
}
15+
16+
@Test
17+
void test3x3Matrix() {
18+
double[][] matrix = {{2, 0, 1}, {3, 0, 0}, {5, 1, 1}};
19+
assertEquals(3, MatrixDeterminant.determinant(matrix), 1e-9);
20+
}
21+
22+
@Test
23+
void test1x1Matrix() {
24+
double[][] matrix = {{5}};
25+
assertEquals(5, MatrixDeterminant.determinant(matrix), 1e-9);
26+
}
27+
28+
@Test
29+
void testSingularMatrix() {
30+
double[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
31+
assertEquals(0, MatrixDeterminant.determinant(matrix), 1e-9);
32+
}
33+
34+
@Test
35+
void testNonSquareMatrix() {
36+
double[][] matrix = {{1, 2, 3}, {4, 5, 6}};
37+
assertThrows(IllegalArgumentException.class, () -> MatrixDeterminant.determinant(matrix));
38+
}
39+
}

0 commit comments

Comments
 (0)