ArrayTester free response problem from the 2018 AP Computer Science A Exam.

ArrayTester is #4 from the from the 2018 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/ap/pdf/ap18-frq-computer-science-a.pdf

## Part (a) – getColumn method

```public static int[] getColumn(int[][] arr2D, int c)
{
int[] column = new int[arr2D.length];

for(int i = 0; i < column.length; i++)
column[i] = arr2D[i][c];

return column;
}
```

## Part (b) – isLatin method

```public static boolean isLatin(int[][] square)
{
if(containsDuplicates(square))
return false;

for(int r = 1; r < square.length; r++)
if( ! hasAllValues(square, square[r]) )
return false;

for(int c = 0; c < square.length; c++)
if( ! hasAllValues(square, getColumn(square, c)))
return false;

return true;
}
```

## hasAllValues method

This method was NOT required to be implemented on the Exam. It is provided in case anyone would like to test their code with it.

Note: The inner loop could be made more efficient by stopping at the first occurrence. I was targeting ease of implementation.

```public static boolean hasAllValues(int[] arr1, int[] arr2)
{
for(int arr1Index = 0; arr1Index < arr1.length; arr1Index++)
{
boolean contains = false;
for(int arr2Index = 0; arr2Index < arr2.length; arr2Index++)
{
if(arr1[arr1Index] == arr2[arr2Index])
contains = true;
}

if( ! contains )
return false;
}

return true;
}
```

## containsDuplicates method

This method was NOT required to be implemented on the Exam. It is provided in case anyone would like to test their code with it.

```public static boolean containsDuplicates(int[] arr)
{
for(int i = 0; i < arr.length; i++)
for(int j = i + 1; j < arr.length; j++)
if(arr[i] == arr[j])
return true;

return false;
}
```

## 5 thoughts on “ArrayTester free response answer”

1. Josh Pudaloff

Nitpicking here but the parameter name for isLatin is “`square`” and not “`squares`

• Brandon Horn

You speak truth.

2. Mark Moylan

alt solution to isLatin only one loop is required

```public static boolean isLatin(int [][] square){
for(int i = 0; i < square.length; i++){
int[] col = getColumn();
if(containsDuplicates(square)
|| !haveAllValues(square, square[i])
|| !haveAllValues(square, col)){
return false;
}
}

return true;
}
```
• Brandon Horn

The logic of a single loop is valid, although there is no reason to run containsDuplicates more than once.

This solution calls getColumn incorrectly and uses the wrong name for hasAllValues.

3. Bryce

For the hasAllValues method, couldn’t you just have one for loop because square.length == square.length? (it’s a square)

Then for the for loop you could have something like this?

```for(int i = 0; i < square.length; i++) {
if(!hasAllValues(square, square[r]) || !hasAllValues(square, getColumn(square, i)))
return false;
}
```