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

Solution

the arraySum method goes through each number in the list, adds them all together, and tells you the total sum of all the numbers.

public class ArrayUtils {
    public static void main(String[] args) {
        int[] arr1 = {1, 3, 2, 7, 3};
        System.out.println("Sum of arr1: " + arraySum(arr1));
    }

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

ArrayUtils.main(null);
Sum of arr1: 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.

Solution

I wanted to try a new way to iterate through a 2D Array instead of the traditional method, so I intorduced a new method getRowSum that calculates the sum of elements in a single row of the 2D array. The rowSums method then uses this getRowSum method to calculate and store the sums of all rows in the 2D array mat1.

public class ArrayUtils {
    public static void main(String[] args) {
        // Define a 2D array 
        int[][] mat1 = {
            {1, 3, 2, 7, 3},
            {10, 10, 4, 6, 2},
            {5, 3, 5, 9, 6},
            {7, 6, 4, 2, 1}
        };

        // Testing rowSums method
        // Call the rowSums method with mat1 as argument and store the returned array
        int[] sums = rowSums(mat1);
        
        // Print a message indicating that row sums are being printed
        System.out.println("Row sums:");
        
        // Loop through each element in the sums array and print it
        for (int sum : sums) {
            System.out.println(sum);
        }
    }

    // Method to calculate row sums of a 2D array
    public static int[] rowSums(int[][] arr2D) {
        // Get the number of rows in the input 2D array
        int rowCount = arr2D.length;
        
        // Create a new integer array to store row sums with the same
        // length as the number of rows
        int[] sums = new int[rowCount];

        // Loop through each row of the 2D array
        for (int i = 0; i < rowCount; i++) {
            // Calculate the sum of the current row using the getRowSum method and store it in sums array
            sums[i] = getRowSum(arr2D[i]);
        }

        // Return the array containing row sums
        return sums;
    }

    // Method to calculate the sum of elements in a 1D array (row)
    public static int getRowSum(int[] row) {
        // Initialize a variable to store the sum of elements in the row
        int sum = 0;
        
        // Loop through each element in the row
        for (int num : row) {
            // Add the current element to the sum
            sum += num;
        }
        
        // Return the sum of elements in the row
        return sum;
    }
}

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

Solution

the code checks if each row in a given 2D array has a unique sum of its elements. If all rows have unique sums, the array is considered diverse, and the method returns true. Otherwise, if any row has a sum that’s the same as another row, the array is not diverse, and the method returns false. The main method uses this method to determine whether two specific 2D arrays are diverse or not and prints the result accordingly.

import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        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("mat1 is");
        System.out.println("diverse? " + isDiverse(mat1)); // should be true for mat1
        System.out.println("mat2 is");
        System.out.println("diverse? " + isDiverse(mat2)); // should be true for mat2
    }
    public static boolean isDiverse(int[][] arr2D) { 
        Set<Integer> set = new HashSet<>(); // set to store unique row sums
// // iterates through each row of the input 2D array using 
// an enhanced for loop 
        for (int[] row : arr2D) {
            int sum = 0;
// iterates through each element of the row using another enhanced 
// for loop and adds each element to sum.
            for (int num : row) {
                sum += num; // calculate row sum
            }
// checks if the sum is not unique in the set, (it was 
// already encountered in a previous row.)
            if (!set.add(sum)) { // if sum not added to set, not unique
                return false; 

            }
        }
        return true; // if all row sums are unique, array is diverse
    }
}

Main.main(null);

mat1 is
diverse? true
mat2 is
diverse? false

Reflection and Key Learnings

This exercise reinforced my understanding of working with 2D arrays in Java. In the provided code, mat1 and mat2 are 2D arrays of integers, each representing a matrix. Manipulating and iterating over 2D arrays is a fundamental skill in Java programming, and this exercise provided an opportunity to practice it. Another thing was The use of the HashSet data structure in the isDiverse method demonstrated the importance of selecting the appropriate data structure for the task at hand. In this case, a HashSet was chosen to efficiently store unique row sums. This choice allowed for constant-time insertion and lookup operations, ensuring an efficient solution to the problem of checking array diversity. Lastly, overall my algorithmic thinking has deeply increased for example: the problem of determining whether a 2D array is diverse requires algorithmic thinking. The isDiverse method employs a simple algorithm to iterate over each row of the array, calculate the sum of its elements, and check if the sum is unique using a set. This exercise encouraged me to think algorithmically and develop a solution to the problem using basic programming constructs.