diff --git a/src/main/java/com/thealgorithms/matrix/MatrixDeterminant.java b/src/main/java/com/thealgorithms/matrix/MatrixDeterminant.java new file mode 100644 index 000000000000..f6921cb6b93e --- /dev/null +++ b/src/main/java/com/thealgorithms/matrix/MatrixDeterminant.java @@ -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; + } +} diff --git a/src/test/java/com/thealgorithms/matrix/MatrixDeterminantTest.java b/src/test/java/com/thealgorithms/matrix/MatrixDeterminantTest.java new file mode 100644 index 000000000000..b6b05c1d5a33 --- /dev/null +++ b/src/test/java/com/thealgorithms/matrix/MatrixDeterminantTest.java @@ -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)); + } +}