Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Matrix Determinant Java
    Hello, does anyone know why i get incorrect test cases for the Matrix Determinant challenge even though my code gives the right output, parameter testing gave me the right answers however for the same test cases i get incorrect when i submit the code. I used an online matrix determinant calculator to get the results for the test cases, my code gives the same result yet it's being flagged as incorrect. Anyway here's my code:
    int[][] extractMatrix(int [][] a, int n, int ln, int col){
    
          int[][] b = new int[n-1][n-1];
    
          int k=0;
          int l=0;
    
          for(int i=0; i<n; i++){
              if(i!=ln){
                  for(int j=0; j<n;j++){
                      if(j!=col){
                          b[k][l] = a[i][j];
                          l++;
                      }
                  }
                  k++;
                  l=0;
              }
          }
          return b;
      }
    
      int getDeterminant(int[][] a, int n){
          if(n==2)
              return a[0][0]*a[1][1] - a[0][1]*a[1][0];
          else{
              boolean negative = false;
              int det = 0;
              for(int i =0; i<n; i++){
                  if(!negative){
                      negative=true;
                      det+= a[0][i]*getDeterminant(extractMatrix(a,n,0,i),n-1);
                  }
                  else{
                      negative = false;
                      det-= a[0][i]*getDeterminant(extractMatrix(a,n,0,i),n-1);
                  }
              }
              return det;
          }
      }
    
      int MatrixDeterminant(String[] strArr) { 
    
        int[][] a;
        int rows=0;
        int cols=0;
        int det = 0;
    
        boolean flag = false;
        for(int i=0; i<strArr.length; i++){
            if(strArr[i].equals("<>")){
                if(!flag)
                    flag=true;
                rows++;
            }
            else{
                if(!flag)
                    cols++;
            }
        }
        rows++;
    
        if(rows!=cols)
           return -1;
        else{
            int n = rows;
            a = new int[n][n];
            int i=0;
            int j=0;
    
            for(int k=0;k<strArr.length;k++){
                if(strArr[k].equals("<>")){
                    i++;
                    j=0;
                }
                else{
                    a[i][j] = Integer.parseInt(strArr[k]);
                    j++;
                }
            }
            return getDeterminant(a,n);
        }
      }
    
    damian333 posted this question on 10/25/15 | matrix, java
    Answers
    Log in to write an answer.