1D & 2D Arrays
- This FRQ was helpful in a lot of ways because it made me go back to the basics and also made me consider new ways to use what I know. The Key Algorithm was 2D Arrays because we used them in part b and c. The 2D arrays were converted into 1D arrays by summing the rows and this conversion was very interesting to me. This is why I think the Key Algorithm is 2D Arrays due to them being used in this FRQ.
Declaration of Data
- I had to remove the declaration of data because it had some issues with liquid. Need to find a way to declare data without having issues.
Part A
// Returns the sum of the entries in the one-dimensional array arr.
public static int arraySum(int[] arr) {
int sum = 0;
for(int n : arr) {
sum = sum + n;
}
return sum;
}
System.out.print(arraySum(arr1)); // Should return 16
16
Part B
// Returns a one-dimensional array in which the entry at index k is the sum of the entries of row k of the two-dimensional array arr2D.
public static int [] rowSums(int[][] arr2D) {
int[] newArray = new int[arr2D.length];
for (int k = 0; k < arr2D.length; k++) {
newArray[k] = arraySum(arr2D[k]);
}
return newArray;
}
System.out.println(Arrays.toString(rowSums(arr2D1))); // Should return [16, 32, 28, 20]
System.out.print(Arrays.toString(rowSums(arr2D2))); // Should return [16, 28, 28, 20]
[16, 32, 28, 20]
[16, 28, 28, 20]
Part C
// Returns true if all rows in arr2D have different row sums; false otherwise.
public static boolean isDiverse(int[][] arr2D) {
int [] diverseArray = rowSums(arr2D);
for (int i = 0; i < diverseArray.length; i++) {
for (int j = i+1; j < diverseArray.length; j++) {
if (diverseArray[i] == diverseArray[j]) {
return false;
}
}
}
return true;
}
System.out.println(isDiverse(arr2D1)); // Should return true
System.out.print(isDiverse(arr2D2)); // Should return false
true
false