Solution to DeterminantFinder practice problem for 2D arrays and recursion

Complete the DeterminantFinder practice problem 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. Throwing exceptions is not part of the AP Computer Science A subset and is not included on the exam.

public class DeterminantFinder
{
  public static boolean determinantDefined(int[][] matrix)
  {
    if (!atLeastOneByOne(matrix))
      return false;

    return matrix.length >= 2 && matrix.length == matrix[0].length;
  }

  public static int findTwoByTwoDeterminant(int[][] matrix)
  {
    if (!(determinantDefined(matrix) && matrix.length == 2 && matrix[0].length == 2))
      throw new IllegalArgumentException();

    return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
  }

  private static int[][] removeRowAndColumn(int[][] matrix, int rowToRemove, int colToRemove)
  {
    if (!(rowToRemove >= 0 && colToRemove >= 0 && matrix.length > rowToRemove && matrix[0].length > colToRemove))
      throw new IllegalArgumentException();

    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)
      {
        System.arraycopy(matrix[row], 0, newMatrix[newRow], 0, colToRemove);
        System.arraycopy(matrix[row], colToRemove + 1, newMatrix[newRow],
            colToRemove, matrix[row].length - (colToRemove + 1));
        newRow++;
      }
    }

    return newMatrix;
  }

  public static int findDeterminant(int[][] matrix)
  {
    if (!determinantDefined(matrix))
      throw new IllegalArgumentException();

    if (matrix.length == 2)
      return findTwoByTwoDeterminant(matrix);

    int oneOrNegativeOne = -1;
    int determinant = 0;

    for (int col = 0; col < matrix[0].length; col++)
    {
      determinant += oneOrNegativeOne * matrix[0][col]
          * findDeterminant(removeRowAndColumn(matrix, 0, col));
      oneOrNegativeOne *= -1;
    }

    return determinant;
  }

  private static boolean atLeastOneByOne(int[][] matrix)
  {
    return matrix != null && matrix.length > 0 && matrix[0].length > 0;
  }
}

Get AP CS Help