|
1 | | -package matrix; |
| 1 | +package com.thealgorithms.matrix; |
2 | 2 |
|
3 | | -public class MatrixDeterminant { |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | +import static org.junit.jupiter.api.Assertions.*; |
4 | 5 |
|
5 | | - public static double determinant(double[][] m) { |
6 | | - int n = m.length; |
7 | | - if (n == 1) return m[0][0]; |
8 | | - if (n == 2) return m[0][0]*m[1][1] - m[0][1]*m[1][0]; |
| 6 | +class MatrixDeterminantTest { |
9 | 7 |
|
10 | | - double det = 0; |
11 | | - for (int c = 0; c < n; c++) { |
12 | | - det += Math.pow(-1, c) * m[0][c] * determinant(minor(m, 0, c)); |
13 | | - } |
14 | | - return det; |
| 8 | + @Test |
| 9 | + void test2x2Matrix() { |
| 10 | + double[][] matrix = {{1, 2}, {3, 4}}; |
| 11 | + assertEquals(-2, MatrixDeterminant.determinant(matrix), 1e-9); |
15 | 12 | } |
16 | 13 |
|
17 | | - private static double[][] minor(double[][] m, int row, int col) { |
18 | | - int n = m.length; |
19 | | - double[][] min = new double[n-1][n-1]; |
20 | | - int r = 0; |
21 | | - for (int i = 0; i < n; i++) { |
22 | | - if (i == row) continue; |
23 | | - int c = 0; |
24 | | - for (int j = 0; j < n; j++) { |
25 | | - if (j == col) continue; |
26 | | - min[r][c++] = m[i][j]; |
27 | | - } |
28 | | - r++; |
29 | | - } |
30 | | - return min; |
| 14 | + @Test |
| 15 | + void test3x3Matrix() { |
| 16 | + double[][] matrix = {{2, 0, 1}, {3, 0, 0}, {5, 1, 1}}; |
| 17 | + assertEquals(3, MatrixDeterminant.determinant(matrix), 1e-9); |
31 | 18 | } |
32 | 19 |
|
33 | | - public static void main(String[] args) { |
34 | | - double[][] a = {{1,2},{3,4}}; |
35 | | - double[][] b = {{2,0,1},{3,0,0},{5,1,1}}; |
36 | | - System.out.println(determinant(a)); // -2 |
37 | | - System.out.println(determinant(b)); // 3 |
| 20 | + @Test |
| 21 | + void test1x1Matrix() { |
| 22 | + double[][] matrix = {{5}}; |
| 23 | + assertEquals(5, MatrixDeterminant.determinant(matrix), 1e-9); |
| 24 | + } |
| 25 | + |
| 26 | + @Test |
| 27 | + void testSingularMatrix() { |
| 28 | + double[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; |
| 29 | + assertEquals(0, MatrixDeterminant.determinant(matrix), 1e-9); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + void testNonSquareMatrix() { |
| 34 | + double[][] matrix = {{1, 2, 3}, {4, 5, 6}}; |
| 35 | + assertThrows(IllegalArgumentException.class, () -> MatrixDeterminant.determinant(matrix)); |
38 | 36 | } |
39 | 37 | } |
0 commit comments