Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions src/main/java/com/thealgorithms/matrix/MatrixDeterminant.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.thealgorithms.matrix;

// Problem: Determinant of a Matrix
// Description: Calculate the determinant of any square matrix using recursion.
// URL: https://en.wikipedia.org/wiki/Determinant

public final class MatrixDeterminant {

private MatrixDeterminant() {
// Prevent instantiation
}

public static double determinant(double[][] m) {
int n = m.length;
for (double[] row : m) {
if (row.length != n) {
throw new IllegalArgumentException("Matrix must be square");
}
}

if (n == 1) {
return m[0][0];
}

if (n == 2) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}

double det = 0;
for (int c = 0; c < n; c++) {
det += Math.pow(-1, c) * m[0][c] * determinant(minor(m, 0, c));
}
return det;
}

private static double[][] minor(double[][] m, int row, int col) {
int n = m.length;
double[][] min = new double[n - 1][n - 1];
int r = 0;

for (int i = 0; i < n; i++) {
if (i == row) {
continue;
}
int c = 0;
for (int j = 0; j < n; j++) {
if (j == col) {
continue;
}
min[r][c++] = m[i][j];
}
r++;
}
return min;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.thealgorithms.matrix;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

class MatrixDeterminantTest {

@Test
void test2x2Matrix() {
double[][] matrix = {{1, 2}, {3, 4}};
assertEquals(-2, MatrixDeterminant.determinant(matrix), 1e-9);
}

@Test
void test3x3Matrix() {
double[][] matrix = {{2, 0, 1}, {3, 0, 0}, {5, 1, 1}};
assertEquals(3, MatrixDeterminant.determinant(matrix), 1e-9);
}

@Test
void test1x1Matrix() {
double[][] matrix = {{5}};
assertEquals(5, MatrixDeterminant.determinant(matrix), 1e-9);
}

@Test
void testSingularMatrix() {
double[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
assertEquals(0, MatrixDeterminant.determinant(matrix), 1e-9);
}

@Test
void testNonSquareMatrix() {
double[][] matrix = {{1, 2, 3}, {4, 5, 6}};
assertThrows(IllegalArgumentException.class, () -> MatrixDeterminant.determinant(matrix));
}
}