Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- *
- * @author Ranajoy
- */
- public class Determinant {
- static void display(int arr[][]){
- int rows = arr.length;
- int cols = arr[0].length;
- for(int i = 0; i < rows; i++){
- for(int j = 0; j < cols; j++){
- System.out.print(arr[i][j] + " ");
- }
- System.out.println("");
- }
- System.out.println("");
- }
- static int calcDeterminant(int arr[][]){
- // Expanding w.r.t first row
- int det = 0;
- int co_factors[][] = new int[2][2];
- for(int j = 0; j < 3; j++){
- // The element is arr[0][j]
- // Calculating the co-factors of
- // arr[0][j]
- int c_i = 0;
- for(int row = 1; row < 3; row++){
- int c_j = 0;
- for(int col = 0; col < 3; col++){
- // The co-factors are present in those columns to which
- // the element arr[0][j] does not belong
- if(col != j){
- co_factors[c_i][c_j] = arr[row][col];
- c_j++;
- }
- }
- c_i++;
- }
- System.out.println("Co-factors of " + arr[0][j] + " are");
- display(co_factors);
- // For even indexed columns the co-factors have a + sign
- // For odd indexed columns the co-factors have a - sign
- if(j % 2 == 0){
- det += arr[0][j] * ((co_factors[0][0] * co_factors[1][1]) -
- ((co_factors[0][1] * co_factors[1][0])));
- }
- else{
- det -= arr[0][j] * ((co_factors[0][0] * co_factors[1][1]) -
- ((co_factors[0][1] * co_factors[1][0])));
- }
- }
- return det;
- }
- public static void main(String[] args) {
- int arr[][] = {
- {1, 2, 3},
- {1, 1, 1},
- {1, 2, 3}
- };
- System.out.println("Determinant = " + calcDeterminant(arr));
- }
- }
Add Comment
Please, Sign In to add comment