mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
Create package prime, matrix and games (#6139)
This commit is contained in:
125
src/main/java/com/thealgorithms/matrix/MatrixRank.java
Normal file
125
src/main/java/com/thealgorithms/matrix/MatrixRank.java
Normal file
@@ -0,0 +1,125 @@
|
||||
package com.thealgorithms.matrix;
|
||||
|
||||
import static com.thealgorithms.matrix.utils.MatrixUtil.validateInputMatrix;
|
||||
|
||||
/**
|
||||
* This class provides a method to compute the rank of a matrix.
|
||||
* In linear algebra, the rank of a matrix is the maximum number of linearly independent rows or columns in the matrix.
|
||||
* For example, consider the following 3x3 matrix:
|
||||
* 1 2 3
|
||||
* 2 4 6
|
||||
* 3 6 9
|
||||
* Despite having 3 rows and 3 columns, this matrix only has a rank of 1 because all rows (and columns) are multiples of each other.
|
||||
* It's a fundamental concept that gives key insights into the structure of the matrix.
|
||||
* It's important to note that the rank is not only defined for square matrices but for any m x n matrix.
|
||||
*
|
||||
* @author Anup Omkar
|
||||
*/
|
||||
public final class MatrixRank {
|
||||
|
||||
private MatrixRank() {
|
||||
}
|
||||
|
||||
private static final double EPSILON = 1e-10;
|
||||
|
||||
/**
|
||||
* @brief Computes the rank of the input matrix
|
||||
*
|
||||
* @param matrix The input matrix
|
||||
* @return The rank of the input matrix
|
||||
*/
|
||||
public static int computeRank(double[][] matrix) {
|
||||
validateInputMatrix(matrix);
|
||||
|
||||
int numRows = matrix.length;
|
||||
int numColumns = matrix[0].length;
|
||||
int rank = 0;
|
||||
|
||||
boolean[] rowMarked = new boolean[numRows];
|
||||
|
||||
double[][] matrixCopy = deepCopy(matrix);
|
||||
|
||||
for (int colIndex = 0; colIndex < numColumns; ++colIndex) {
|
||||
int pivotRow = findPivotRow(matrixCopy, rowMarked, colIndex);
|
||||
if (pivotRow != numRows) {
|
||||
++rank;
|
||||
rowMarked[pivotRow] = true;
|
||||
normalizePivotRow(matrixCopy, pivotRow, colIndex);
|
||||
eliminateRows(matrixCopy, pivotRow, colIndex);
|
||||
}
|
||||
}
|
||||
return rank;
|
||||
}
|
||||
|
||||
private static boolean isZero(double value) {
|
||||
return Math.abs(value) < EPSILON;
|
||||
}
|
||||
|
||||
private static double[][] deepCopy(double[][] matrix) {
|
||||
int numRows = matrix.length;
|
||||
int numColumns = matrix[0].length;
|
||||
double[][] matrixCopy = new double[numRows][numColumns];
|
||||
for (int rowIndex = 0; rowIndex < numRows; ++rowIndex) {
|
||||
System.arraycopy(matrix[rowIndex], 0, matrixCopy[rowIndex], 0, numColumns);
|
||||
}
|
||||
return matrixCopy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The pivot row is the row in the matrix that is used to eliminate other rows and reduce the matrix to its row echelon form.
|
||||
* The pivot row is selected as the first row (from top to bottom) where the value in the current column (the pivot column) is not zero.
|
||||
* This row is then used to "eliminate" other rows, by subtracting multiples of the pivot row from them, so that all other entries in the pivot column become zero.
|
||||
* This process is repeated for each column, each time selecting a new pivot row, until the matrix is in row echelon form.
|
||||
* The number of pivot rows (rows with a leading entry, or pivot) then gives the rank of the matrix.
|
||||
*
|
||||
* @param matrix The input matrix
|
||||
* @param rowMarked An array indicating which rows have been marked
|
||||
* @param colIndex The column index
|
||||
* @return The pivot row index, or the number of rows if no suitable pivot row was found
|
||||
*/
|
||||
private static int findPivotRow(double[][] matrix, boolean[] rowMarked, int colIndex) {
|
||||
int numRows = matrix.length;
|
||||
for (int pivotRow = 0; pivotRow < numRows; ++pivotRow) {
|
||||
if (!rowMarked[pivotRow] && !isZero(matrix[pivotRow][colIndex])) {
|
||||
return pivotRow;
|
||||
}
|
||||
}
|
||||
return numRows;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief This method divides all values in the pivot row by the value in the given column.
|
||||
* This ensures that the pivot value itself will be 1, which simplifies further calculations.
|
||||
*
|
||||
* @param matrix The input matrix
|
||||
* @param pivotRow The pivot row index
|
||||
* @param colIndex The column index
|
||||
*/
|
||||
private static void normalizePivotRow(double[][] matrix, int pivotRow, int colIndex) {
|
||||
int numColumns = matrix[0].length;
|
||||
for (int nextCol = colIndex + 1; nextCol < numColumns; ++nextCol) {
|
||||
matrix[pivotRow][nextCol] /= matrix[pivotRow][colIndex];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief This method subtracts multiples of the pivot row from all other rows,
|
||||
* so that all values in the given column of other rows will be zero.
|
||||
* This is a key step in reducing the matrix to row echelon form.
|
||||
*
|
||||
* @param matrix The input matrix
|
||||
* @param pivotRow The pivot row index
|
||||
* @param colIndex The column index
|
||||
*/
|
||||
private static void eliminateRows(double[][] matrix, int pivotRow, int colIndex) {
|
||||
int numRows = matrix.length;
|
||||
int numColumns = matrix[0].length;
|
||||
for (int otherRow = 0; otherRow < numRows; ++otherRow) {
|
||||
if (otherRow != pivotRow && !isZero(matrix[otherRow][colIndex])) {
|
||||
for (int col2 = colIndex + 1; col2 < numColumns; ++col2) {
|
||||
matrix[otherRow][col2] -= matrix[pivotRow][col2] * matrix[otherRow][colIndex];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.thealgorithms.matrix;
|
||||
|
||||
// Problem Statement
|
||||
|
||||
import com.thealgorithms.matrix.utils.MatrixUtil;
|
||||
|
||||
/*
|
||||
We have given an array of m x n (where m is the number of rows and n is the number of columns).
|
||||
Print the new matrix in such a way that the new matrix is the mirror image of the original matrix.
|
||||
@@ -17,41 +20,17 @@ public final class MirrorOfMatrix {
|
||||
private MirrorOfMatrix() {
|
||||
}
|
||||
|
||||
public static int[][] mirrorMatrix(final int[][] originalMatrix) {
|
||||
if (originalMatrix == null) {
|
||||
// Handle invalid input
|
||||
return null;
|
||||
}
|
||||
if (originalMatrix.length == 0) {
|
||||
return new int[0][0];
|
||||
}
|
||||
|
||||
checkInput(originalMatrix);
|
||||
public static double[][] mirrorMatrix(final double[][] originalMatrix) {
|
||||
MatrixUtil.validateInputMatrix(originalMatrix);
|
||||
|
||||
int numRows = originalMatrix.length;
|
||||
int numCols = originalMatrix[0].length;
|
||||
|
||||
int[][] mirroredMatrix = new int[numRows][numCols];
|
||||
double[][] mirroredMatrix = new double[numRows][numCols];
|
||||
|
||||
for (int i = 0; i < numRows; i++) {
|
||||
mirroredMatrix[i] = reverseRow(originalMatrix[i]);
|
||||
mirroredMatrix[i] = MatrixUtil.reverseRow(originalMatrix[i]);
|
||||
}
|
||||
return mirroredMatrix;
|
||||
}
|
||||
private static int[] reverseRow(final int[] inRow) {
|
||||
int[] res = new int[inRow.length];
|
||||
for (int i = 0; i < inRow.length; ++i) {
|
||||
res[i] = inRow[inRow.length - 1 - i];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private static void checkInput(final int[][] matrix) {
|
||||
// Check if all rows have the same number of columns
|
||||
for (int i = 1; i < matrix.length; i++) {
|
||||
if (matrix[i].length != matrix[0].length) {
|
||||
throw new IllegalArgumentException("The input is not a matrix.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.thealgorithms.matrix.matrixexponentiation;
|
||||
|
||||
import java.util.Scanner;
|
||||
import com.thealgorithms.matrix.utils.MatrixUtil;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* @author Anirudh Buvanesh (https://github.com/anirudhb11) For more information
|
||||
@@ -12,39 +13,11 @@ public final class Fibonacci {
|
||||
}
|
||||
|
||||
// Exponentiation matrix for Fibonacci sequence
|
||||
private static final int[][] FIB_MATRIX = {{1, 1}, {1, 0}};
|
||||
private static final int[][] IDENTITY_MATRIX = {{1, 0}, {0, 1}};
|
||||
// First 2 fibonacci numbers
|
||||
private static final int[][] BASE_FIB_NUMBERS = {{1}, {0}};
|
||||
private static final BigDecimal ONE = BigDecimal.valueOf(1);
|
||||
private static final BigDecimal ZERO = BigDecimal.valueOf(0);
|
||||
|
||||
/**
|
||||
* Performs multiplication of 2 matrices
|
||||
*
|
||||
* @param matrix1
|
||||
* @param matrix2
|
||||
* @return The product of matrix1 and matrix2
|
||||
*/
|
||||
private static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) {
|
||||
// Check if matrices passed can be multiplied
|
||||
int rowsInMatrix1 = matrix1.length;
|
||||
int columnsInMatrix1 = matrix1[0].length;
|
||||
|
||||
int rowsInMatrix2 = matrix2.length;
|
||||
int columnsInMatrix2 = matrix2[0].length;
|
||||
|
||||
assert columnsInMatrix1 == rowsInMatrix2;
|
||||
int[][] product = new int[rowsInMatrix1][columnsInMatrix2];
|
||||
for (int rowIndex = 0; rowIndex < rowsInMatrix1; rowIndex++) {
|
||||
for (int colIndex = 0; colIndex < columnsInMatrix2; colIndex++) {
|
||||
int matrixEntry = 0;
|
||||
for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1; intermediateIndex++) {
|
||||
matrixEntry += matrix1[rowIndex][intermediateIndex] * matrix2[intermediateIndex][colIndex];
|
||||
}
|
||||
product[rowIndex][colIndex] = matrixEntry;
|
||||
}
|
||||
}
|
||||
return product;
|
||||
}
|
||||
private static final BigDecimal[][] FIB_MATRIX = {{ONE, ONE}, {ONE, ZERO}};
|
||||
private static final BigDecimal[][] IDENTITY_MATRIX = {{ONE, ZERO}, {ZERO, ONE}};
|
||||
|
||||
/**
|
||||
* Calculates the fibonacci number using matrix exponentiaition technique
|
||||
@@ -53,26 +26,17 @@ public final class Fibonacci {
|
||||
* Outputs the nth * fibonacci number
|
||||
* @return a 2 X 1 array as { {F_n+1}, {F_n} }
|
||||
*/
|
||||
public static int[][] fib(int n) {
|
||||
public static BigDecimal[][] fib(int n) {
|
||||
if (n == 0) {
|
||||
return IDENTITY_MATRIX;
|
||||
} else {
|
||||
int[][] cachedResult = fib(n / 2);
|
||||
int[][] matrixExpResult = matrixMultiplication(cachedResult, cachedResult);
|
||||
BigDecimal[][] cachedResult = fib(n / 2);
|
||||
BigDecimal[][] matrixExpResult = MatrixUtil.multiply(cachedResult, cachedResult).get();
|
||||
if (n % 2 == 0) {
|
||||
return matrixExpResult;
|
||||
} else {
|
||||
return matrixMultiplication(FIB_MATRIX, matrixExpResult);
|
||||
return MatrixUtil.multiply(FIB_MATRIX, matrixExpResult).get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Returns [0, 1, 1, 2, 3, 5 ..] for n = [0, 1, 2, 3, 4, 5.. ]
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int n = sc.nextInt();
|
||||
int[][] result = matrixMultiplication(fib(n), BASE_FIB_NUMBERS);
|
||||
System.out.println("Fib(" + n + ") = " + result[1][0]);
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
|
||||
133
src/main/java/com/thealgorithms/matrix/utils/MatrixUtil.java
Normal file
133
src/main/java/com/thealgorithms/matrix/utils/MatrixUtil.java
Normal file
@@ -0,0 +1,133 @@
|
||||
package com.thealgorithms.matrix.utils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* @author: caos321
|
||||
* @date: 31 October 2021 (Sunday)
|
||||
*/
|
||||
public final class MatrixUtil {
|
||||
|
||||
private MatrixUtil() {
|
||||
}
|
||||
|
||||
private static boolean isValid(final BigDecimal[][] matrix) {
|
||||
return matrix != null && matrix.length > 0 && matrix[0].length > 0;
|
||||
}
|
||||
|
||||
private static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length && matrix1[0].length == matrix2[0].length;
|
||||
}
|
||||
|
||||
private static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length;
|
||||
}
|
||||
|
||||
public static void validateInputMatrix(double[][] matrix) {
|
||||
if (matrix == null) {
|
||||
throw new IllegalArgumentException("The input matrix cannot be null");
|
||||
}
|
||||
if (matrix.length == 0) {
|
||||
throw new IllegalArgumentException("The input matrix cannot be empty");
|
||||
}
|
||||
if (!hasValidRows(matrix)) {
|
||||
throw new IllegalArgumentException("The input matrix cannot have null or empty rows");
|
||||
}
|
||||
if (isJaggedMatrix(matrix)) {
|
||||
throw new IllegalArgumentException("The input matrix cannot be jagged");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasValidRows(double[][] matrix) {
|
||||
for (double[] row : matrix) {
|
||||
if (row == null || row.length == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Checks if the input matrix is a jagged matrix.
|
||||
* Jagged matrix is a matrix where the number of columns in each row is not the same.
|
||||
*
|
||||
* @param matrix The input matrix
|
||||
* @return True if the input matrix is a jagged matrix, false otherwise
|
||||
*/
|
||||
private static boolean isJaggedMatrix(double[][] matrix) {
|
||||
int numColumns = matrix[0].length;
|
||||
for (double[] row : matrix) {
|
||||
if (row.length != numColumns) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
|
||||
if (!hasEqualSizes(matrix1, matrix2)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final int rowSize = matrix1.length;
|
||||
final int columnSize = matrix1[0].length;
|
||||
|
||||
final BigDecimal[][] result = new BigDecimal[rowSize][columnSize];
|
||||
|
||||
IntStream.range(0, rowSize).forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> {
|
||||
final BigDecimal value1 = matrix1[rowIndex][columnIndex];
|
||||
final BigDecimal value2 = matrix2[rowIndex][columnIndex];
|
||||
|
||||
result[rowIndex][columnIndex] = operation.apply(value1, value2);
|
||||
}));
|
||||
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return operate(matrix1, matrix2, BigDecimal::add);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return operate(matrix1, matrix2, BigDecimal::subtract);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
if (!canMultiply(matrix1, matrix2)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
final int size = matrix1[0].length;
|
||||
|
||||
final int matrix1RowSize = matrix1.length;
|
||||
final int matrix2ColumnSize = matrix2[0].length;
|
||||
|
||||
final BigDecimal[][] result = new BigDecimal[matrix1RowSize][matrix2ColumnSize];
|
||||
|
||||
IntStream.range(0, matrix1RowSize)
|
||||
.forEach(rowIndex
|
||||
-> IntStream.range(0, matrix2ColumnSize)
|
||||
.forEach(columnIndex
|
||||
-> result[rowIndex][columnIndex] = IntStream.range(0, size)
|
||||
.mapToObj(index -> {
|
||||
final BigDecimal value1 = matrix1[rowIndex][index];
|
||||
final BigDecimal value2 = matrix2[index][columnIndex];
|
||||
|
||||
return value1.multiply(value2);
|
||||
})
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add)));
|
||||
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
public static double[] reverseRow(final double[] inRow) {
|
||||
double[] res = new double[inRow.length];
|
||||
for (int i = 0; i < inRow.length; ++i) {
|
||||
res[i] = inRow[inRow.length - 1 - i];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user