Question 1:

(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.

(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.

(c) A two-dimensional array is diverse if no two of its rows have entries that sum to the same value. In the following examples, the array mat1 is diverse because each row sum is different, but the array mat2 is not diverse because the first and last rows have the same sum. 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.

Key Algorithm: 2D Arrays + Arrays

public class Main {
    public static int arraySum (int[] arr) //Part A
    {
        int sum = 0;
        for (int i = 0; i < arr.length; i++)
        {
            sum += arr[i];
        }
        return sum;
    }

    public static int[] rowSums(int[][] arr2D) { //Part B
        int[] sums = new int[arr2D.length];
        for (int i = 0; i < arr2D.length; i++) {
            int sum = 0;
            for (int j = 0; j < arr2D[i].length; j++) {
                sum += arr2D[i][j];
            }
            sums[i] = sum;
        }
        return sums;
    }
    
    
    public static boolean isDiverse(int[][] arr2D) //Part C
    {
        int[] sums = rowSums(arr2D);
        HashSet<Integer> set = new HashSet<>();
        for (int num : sums) {
            if (set.contains(num)) {
                return false;
            }
            set.add(num);
        }

        return true;
    }

    public static void main(String[] args)
    {
        int[] arr2 = {1, 3, 2, 7, 3};
        System.out.println(arraySum(arr2));
        int[][] arr1 = {
            {1, 1, 5, 3, 4},
            {12, 7, 6, 1, 9},
            {8, 11, 10, 2, 5},
            {3, 2, 3, 0, 6}
        };        
        int[] sums = rowSums(arr1);
        for (int i = 0; i < sums.length; i++)
        {
            System.out.print(sums[i] + " ");
        }
        System.out.println();
        System.out.println(isDiverse(arr1));
    }
}

Main.main(null);
16
14 35 36 14 
false