Add MatrixRank (#4571)

* feat: adding matrix rank algorithm

* fix: formatting

* fix: adding comments, refactor and handling edge cases

* refactor: minor refactor

* enhancement: check matrix validity

* refactor: minor refactor and fixes

* Update src/main/java/com/thealgorithms/maths/MatrixRank.java

* feat: add unit test to check if input matrix is not modified while calculating the rank

---------

Co-authored-by: Anup Omkar <anup_omkar@intuit.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
This commit is contained in:
Anup Omkar
2023-10-25 19:04:05 +05:30
committed by GitHub
parent a4711d61d8
commit 9dde8a7808
2 changed files with 209 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class MatrixRankTest {
private static Stream<Arguments> validInputStream() {
return Stream.of(Arguments.of(3, new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}), Arguments.of(0, new double[][] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}), Arguments.of(1, new double[][] {{1}}), Arguments.of(2, new double[][] {{1, 2}, {3, 4}}),
Arguments.of(2, new double[][] {{3, -1, 2}, {-3, 1, 2}, {-6, 2, 4}}), Arguments.of(3, new double[][] {{2, 3, 0, 1}, {1, 0, 1, 2}, {-1, 1, 1, -2}, {1, 5, 3, -1}}), Arguments.of(1, new double[][] {{1, 2, 3}, {3, 6, 9}}),
Arguments.of(2, new double[][] {{0.25, 0.5, 0.75, 2}, {1.5, 3, 4.5, 6}, {1, 2, 3, 4}}));
}
private static Stream<Arguments> invalidInputStream() {
return Stream.of(Arguments.of((Object) new double[][] {{1, 2}, {10}, {100, 200, 300}}), // jagged array
Arguments.of((Object) new double[][] {}), // empty matrix
Arguments.of((Object) new double[][] {{}, {}}), // empty row
Arguments.of((Object) null), // null matrix
Arguments.of((Object) new double[][] {{1, 2}, null}) // null row
);
}
@ParameterizedTest
@MethodSource("validInputStream")
void computeRankTests(int expectedRank, double[][] matrix) {
int originalHashCode = Arrays.deepHashCode(matrix);
int rank = MatrixRank.computeRank(matrix);
int newHashCode = Arrays.deepHashCode(matrix);
assertEquals(expectedRank, rank);
assertEquals(originalHashCode, newHashCode);
}
@ParameterizedTest
@MethodSource("invalidInputStream")
void computeRankWithInvalidMatrix(double[][] matrix) {
assertThrows(IllegalArgumentException.class, () -> MatrixRank.computeRank(matrix));
}
}