The ArrayTester
FRQ has you working with 2 methods inside a class named ArrayTester
. There were also two methods, hasAllValues
and containsDuplicates
that were listed as Implementation Not Shown. When you see this on a FRQ you almost certinly will be calling those methods somewhere in your solution. Otherwise they wouldn’t have bothered listing them.
Part A, getColumn
tasked you with implementing a method that creates an array out of the values in a single column in a matrix. Consider the following matrix mat
.
Using mat
the call getColumn(mat, 2)
should return the array [3, 7, 11, 15, 19]
which are the values in column 2. Remember that in Java arrays are zero-indexed.
public static int[] getColumn(int[][] arr2D, int c) {
int[] out = new int[arr2D.length];
for (int r=0; r<arr2D.length; r++) {
out[r] = arr2D[r][c];
}
return out;
}
The second part has you check if a given matrix is a Latin Square. It takes 3 conditions for a matrix to be a Latin Square.
For example, this is a Latin Square
Note that the first row contains the values 1 through 5 without any duplicates. And each row and column also contains the values 1 through 5.
We’re also told that there are the same number of rows and columns.
public static boolean isLatin(int[][] square) {
int[] firstRow = square[0];
if (containsDuplicates(firstRow)) {
return false;
}
for (int r=1; r<square.length; r++) {
if (!hasAllValues(firstRow, square[r])) {
return false;
}
}
for (int c=0; c<square[0].length; c++) {
if (!hasAllValues(firstRow, getColumn(square, c))) {
return false;
}
}
return true;
}
First check calls the containsDuplicates
method to make sure that all values in the first row are unique. Then a pair of loops go through each row and then each column to check that every row and column contain the same values as the first row. Notice that we’re calling the hasAllValues
each time and using the getColumn
method we implemented in part A to check the columns.