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
/** Returns the sum of the entries in the one-dimensional array arr.
*/
public static int arraySum (int[] arr){
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
System.out.println(arraySum(new int[]{1,3,2,7,3}));
16
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.
/** 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 numRows = arr2D.length;
int[] sums = new int[numRows];
for (int i = 0; i < numRows; i++) {
sums[i] = arraySum(arr2D[i]);
}
return sums;
}
int[][] arr2D = {
{1, 3, 2, 7, 3},
{10, 10, 4, 6, 2},
{5, 3, 5, 9, 6},
{7, 6, 4, 2, 1}
};
int[] rowSumsArray = rowSums(arr2D);
for (int sum : rowSumsArray) {
System.out.print(sum + " ");
}
16 32 28 20
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
public static boolean isDiverse(int[][] arr2D) {
int[] rowSumsArray = rowSums(arr2D);
// Check for uniqueness of row sums
for (int i = 0; i < rowSumsArray.length - 1; i++) {
for (int j = i + 1; j < rowSumsArray.length; j++) {
if (rowSumsArray[i] == rowSumsArray[j]) {
return false; // If any two row sums are equal, return false
}
}
}
return true; // If all row sums are unique, return true
}
int[][] mat1 = {
{1, 3, 2, 7, 3},
{10, 10, 4, 6, 2},
{5, 3, 5, 9, 6},
{7, 6, 4, 2, 1}
};
int[][] mat2 = {
{1, 1, 5, 3, 4},
{12, 7, 6, 1, 9},
{8, 11, 10, 2, 5},
{3, 2, 3, 0, 6}
};
System.out.println("Is mat1 diverse? " + isDiverse(mat1)); // Should print true
System.out.println("Is mat2 diverse? " + isDiverse(mat2)); // Should print false
Is mat1 diverse? true
Is mat2 diverse? false