`DiverseArray`

is #1 from the from the 2015 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap15_frq_computer_science_a.pdf

## Part (a) `arraySum`

method

```
public static int arraySum(int[] arr)
{
int sum = 0;
for(int value : arr)
sum += value;
return sum;
}
```

On the free response, when in doubt, use a regular loop (`for`

or `while`

). See Enhanced for loop exercises for information on when enhanced `for`

loops are appropriate, and to practice with them.

## Part (b) `rowSums`

method

```
public static int[] rowSums(int[][] arr2D)
{
int[] sums = new int[arr2D.length];
for(int i = 0; i < sums.length; i++)
sums[i] = arraySum(arr2D[i]);
return sums;
}
```

The problem requires that `rowSums`

call `arraySum`

so the 2D array `arr2D`

must be treated as an array of 1D arrays. `arr2D[i]`

stores a reference to the 1D array representing row `i`

of `arr2D`

. See Treating a 2D array as an array of 1D arrays for additional details.

A regular `for`

loop is appropriate here since the index is needed for both `sums`

and `arr2D`

.

## Part (c) `isDiverse`

method

```
public static boolean isDiverse(int[][] arr2D)
{
int[] sums = rowSums(arr2D);
for(int i = 0; i < sums.length; i++)
for(int j = i + 1; j < sums.length; j++)
if(sums[i] == sums[j])
return false;
return true;
}
```

I’m not usually a proponent of using nested loops to traverse a 1D array; however, they are a simple solution here. An alternative solution is to sort `sums`

(not `arr2D`

) then check for adjacent duplicate values. A `Map`

could also be used; however, that is outside the scope of AP CS A.

## 2015 AP CS Exam Free Response Solutions

- HiddenWord Free Response Solution
- SparseArray Free Response Solution
- NumberGroup Free Response Solution