Complete the MatrixManipulator exercise before reviewing the solution.
Review the MatrixManipulator 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.
addable method
public static boolean addable(int[][] first, int[][] second)
{
return first.length == second.length
&& first[0].length == second[0].length;
}
add method
public static int[][] add(int[][] first, int[][] second)
{
int[][] sum = new int[first.length][first[0].length];
for (int row = 0; row < sum.length; row++)
for (int col = 0; col < sum[0].length; col++)
sum[row][col] = first[row][col] + second[row][col];
return sum;
}
multiplyByScalar method
public static int[][] multiplyByScalar(int scalar, int[][] matrix)
{
int[][] scalarProduct = new int[matrix.length][matrix[0].length];
for (int row = 0; row < scalarProduct.length; row++)
for (int col = 0; col < scalarProduct[0].length; col++)
scalarProduct[row][col] = matrix[row][col] * scalar;
return scalarProduct;
}
multipliable method
public static boolean multipliable(int[][] first, int[][] second)
{
return first[0].length == second.length;
}
This differs slightly from the code in the Java file linked above.
multiply(int[][], int, int[][], int) method
public static int multiply(int[][] first, int row, int[][] second, int col)
{
int sumOfProducts = 0;
for (int i = 0; i < first[row].length; i++)
sumOfProducts += first[row][i] * second[i][col];
return sumOfProducts;
}
multiply(int[][], int[][]) method
public static int[][] multiply(int[][] first, int[][] second)
{
int[][] product = new int[first.length][second[0].length];
for (int row = 0; row < product.length; row++)
for (int col = 0; col < product[0].length; col++)
product[row][col] = multiply(first, row, second, col);
return product;
}
Additional 2D array resources
- Intro to 2D arrays
- 2D array exercises
- Mazer FR
- Droppy FR
- Flight FR
- DeterminantFinder exercise
- Enhanced for loop exercises (including with 2D arrays)