test: DeterminantOfMatrix (#5376)

This commit is contained in:
Alex Klymenko 2024-08-24 10:38:16 +02:00 committed by GitHub
parent aefc8fd4b8
commit 84fb717509
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 57 additions and 21 deletions

View File

@ -1,7 +1,5 @@
package com.thealgorithms.maths;
import java.util.Scanner;
/*
* @author Ojasva Jain
* Determinant of a Matrix Wikipedia link: https://en.wikipedia.org/wiki/Determinant
@ -10,8 +8,13 @@ public final class DeterminantOfMatrix {
private DeterminantOfMatrix() {
}
// Determinant calculator
//@return determinant of the input matrix
/**
* Calculates the determinant of a given matrix.
*
* @param a the input matrix
* @param n the size of the matrix
* @return the determinant of the matrix
*/
static int determinant(int[][] a, int n) {
int det = 0;
int sign = 1;
@ -41,21 +44,4 @@ public final class DeterminantOfMatrix {
}
return det;
}
// Driver Method
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Input Matrix
System.out.println("Enter matrix size (Square matrix only)");
int n = in.nextInt();
System.out.println("Enter matrix");
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println(determinant(a, n));
in.close();
}
}

View File

@ -0,0 +1,50 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class DeterminantOfMatrixTest {
@Test
public void testDeterminant2x2Matrix() {
int[][] matrix = {{1, 2}, {3, 4}};
int expected = -2;
assertEquals(expected, DeterminantOfMatrix.determinant(matrix, 2));
}
@Test
public void testDeterminant3x3Matrix() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int expected = 0;
assertEquals(expected, DeterminantOfMatrix.determinant(matrix, 3));
}
@Test
public void testDeterminant3x3MatrixNonZero() {
int[][] matrix = {{1, 2, 3}, {0, 1, 4}, {5, 6, 0}};
int expected = 1;
assertEquals(expected, DeterminantOfMatrix.determinant(matrix, 3));
}
@Test
public void testDeterminant1x1Matrix() {
int[][] matrix = {{7}};
int expected = 7;
assertEquals(expected, DeterminantOfMatrix.determinant(matrix, 1));
}
@Test
public void testDeterminant4x4Matrix() {
int[][] matrix = {{1, 0, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}};
int expected = 0;
assertEquals(expected, DeterminantOfMatrix.determinant(matrix, 4));
}
@Test
public void testDeterminant4x4MatrixZero() {
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int expected = 0;
assertEquals(expected, DeterminantOfMatrix.determinant(matrix, 4));
}
}