public class CodeWar { public static int[][] buildSubmatrix(int[][] matrix, int r, int c) { int size = matrix.length - 1; int result[][] = new int[size][size]; int a = 0, b = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { if (i != 0 && j != c) { result[a][b] = matrix[i][j]; b++; } } if (i != r) { a++; b = 0; } } return result; } public static int determinant(int[][] matrix) { if (matrix.length == 1) return matrix[0][0]; int sign = 1; int sum = 0; for (int i = 0; i < matrix[0].length; i++) { int n = matrix[0][i]; int submatrix[][] = buildSubmatrix(matrix, 0,i); sum += sign * n * determinant(submatrix); sign = sign * -1; } return sum; } public static void main(String arg[]) { int[][] matrix = { { -2, -1,2 }, { 2,1,4 }, { -3,3,1 } }; System.out.println(determinant(matrix)); } }
Sunday, September 15, 2024
Determinant of a matrix
This little program calculates the determinant of an matrix.. using recursion. You don't even need ad - bc for a 2x2 [[a b][c d]]
https://en.wikipedia.org/wiki/Determinant
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment