Complete the DeterminantFinder exercise before reviewing the solution.

Review the DeterminantFinder solution with AP CS Tutor Brandon Horn.

The method documentation from the original practice problem has been omitted. The code in the Java file throws exceptions when the preconditions are not met. The code on this page does not throw exceptions. Throwing exceptions is not part of the AP Computer Science A Java Subset and is not included on the AP CS A Exam.

DeterminantFinder.java

determinantDefined method

public static boolean determinantDefined(int[][] matrix)
{
    return matrix.length >= 2 && matrix.length == matrix[0].length;
}

findTwoByTwoDeterminant method

public static int findTwoByTwoDeterminant(int[][] matrix)
{
    return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}

withoutRowAndColumn method

public static int[][] withoutRowAndColumn(int[][] matrix, int rowToRemove, int colToRemove)
{
    int[][] newMatrix = new int[matrix.length - 1][matrix[0].length - 1];
    int newRow = 0;

    for (int row = 0; row < matrix.length; row++)
    {
        if (row != rowToRemove)
        {
            for(int col = 0; col < colToRemove; col++)
                newMatrix[newRow][col] = matrix[row][col];
            
            for(int col = colToRemove + 1; col < matrix[0].length; col++)
                newMatrix[newRow][col - 1] = matrix[row][col];
            
            newRow++;
        }
    }

    return newMatrix;
}

findDeterminant method

public static int findDeterminant(int[][] matrix)
{
    final int ROW = 0;
    
    int determinant = 0;

    for (int col = 0; col < matrix[0].length; col++)
    {
        int[][] smallerMatrix = withoutRowAndColumn(matrix, ROW, col);
        
        int part = findDeterminant(smallerMatrix);
        part *= matrix[ROW][col];
        
        if(col % 2 == 0)
            determinant += part;
        else
            determinant -= part;
    }

    return determinant;
}

Comments

Comment on DeterminantFinder