2015 FRQ Question 1
None
Question 1: Arrays/ ArrayLists
Part A: Write a static method arraySum that calculates and returns the sum of the entries in a specified one-dimensional array. The following example shows an array arr1 and the value returned by a call to arraySum.
// Part (a)
int[] exampleArray2D = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public static int arraySum(int[] arr) {
int sum = 0; // Initialize sum to 0
for (int value : arr) {
sum += value;
}
return sum; // Return the total sum
}
System.out.println(arraySum(exampleArray2D));
45
Part B: Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [r] [c] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.
```java
// Part (b)
int[][] exampleArray2D = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] exampleArray2D = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
}
public static int[] rowSums(int[][] arr2D) {
int[] sums = new int[arr2D.length];
for (int i = 0; i < arr2D.length; i++) {
sums[i] = arraySum(arr2D[i]);
}
return sums;
}
}
System.out.println(Arrays.toString(rowSums(exampleArray2D)));
[6, 15, 24]
Part C: Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false.
```java
// Part (c)
int[][] exampleArray2D = {
{1, 2, 3},
{4, 8, 6},
{7, 8, 9}
};
public static boolean isDiverse(int[][] arr2D) {
int[] rowSums = rowSums(arr2D);
for (int i = 0; i < rowSums.length - 1; i++) {
for (int j = i + 1; j < rowSums.length; j++) {
if (rowSums[i] == rowSums[j]) {
return false;
}
}
}
return true;
}
System.out.println(isDiverse(exampleArray2D));
true
FRQ 1 Reflection
I found this FRQ to not be too difficult due to my experiences both teaching the Array/ Arraylists lesson in trimester 1 and its constant use in the ASL AI project. The isDiverse function, part c, took the most time out of the three due to me getting some errors with index out of bounds for i, but by adding the -1 to the end of rowSums.length, I managed to fix this issue. I had also already seen the sum of an array in another piece of code I made in trimester 1, but since then I feel much more confident about arrays/ arraylists.