Question 1: Arrays/Arraylists
Question 1a
1a) This question involves reasoning about one-dimensional and two-dimensional arrays of integers. You will write three static methods, all of which are in a single enclosing class, named DiverseArray (not shown). The first method returns the sum of the values of a one-dimensional array; the second method returns an array that represents the sums of the rows of a two-dimensional array; and the third method analyzes row sums.
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.
public class Main {
public static void main(String[] args) {
// number of employees in each city
int[] employees = {1000, 2600, 4200, 5800};
System.out.println("There are " + arraySum(employees) + " employees registered into Jinder");
}
}
public static int arraySum(int[] arr) {
int sum = 0;
for (int num : arr) { // iteration
sum += num;
}
return sum;
}
Main.main(null);
Output:
There are 13600 employees registered into Jinder
1a Explanation
The logic that I used to write the arraySum
method was mostly based on iterating through all of elements of arr
. While iterating, I added the value of each element to the variable sum
, which was initialized to a value of 0, and used a for-each loop for convenience (since I am not modifying the elements of arr
while iterating through it). Finally, I returned the value of sum
at the end. My test code for this was inspired by my project as I used the arraySum
method to find the (hypothetical) total number of employees logged into the website.
Question 1b
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.
public class Main {
public static void main(String[] args) {
// number of employees in each city in each occupation
int[][] employees = {
{100, 200, 300, 400},
{500, 600, 700, 800},
{900, 1000, 1100, 1200}
};
String[] cities={"San Diego, CA", "Los Angeles, CA", "San Francisco, CA"};
int[] sums = rowSums(employees);
System.out.println("Employees by City:");
for (int i = 0; i < sums.length; i++) {
System.out.println("cities[i] + " has " + sums[i]+ "employees);
}
}
}
public static int[] rowSums(int[][] arr2D) {
int[] sums = new int[arr2D.length]; // Initialize an array to store row sums
// Iterate through each row
for (int i = 0; i < arr2D.length; i++) {
// Calculate sum of current row using arraySum method
sums[i] = arraySum(arr2D[i]);
}
return sums;
}
Main.main(null);
Output:
Employees by City:
San Diego, CA has 1000 employees
Los Angeles, CA has 2600 employees
San Francisco, CA has 4200 employees
1b Explanation
I started the rowSums
method by initializing an array of integers called sums
and then iterated through the different arrays within arr2D
in order to compute the sum of the arrays using arraySum()
and set each element at the corresponding index to arraySum(arr2D[i])
. After that, I returned sums
as the output of the method. I couldn’t use a for-each loop because I had to iterate through the indices of arr2D
rather than its elements. I implemented this in a similar fashion as 1a and changed my array of number of employees to be a 2D array with employee counts being classified by both location and occupation.
Question 1c
PART 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.
public class Main {
public static void main(String[] args) {
// employee count by location and occupation for 1st company
int[][] comp1 = {
{100, 200, 300},
{400, 500, 600},
{700, 800, 900}
};
// employee count by location and occupation for 2nd company
int[][] comp2 = {
{100, 400, 700},
{200, 500, 800},
{300, 600, 600}
};
// hypothetical testing of isDiverse method
System.out.println("Company 1 is diverse: " + isDiverse(comp1)); // this should output to true
System.out.println("Company 2 is diverse: " + isDiverse(comp2)); // this should output to false
}
// given method from frq
public static boolean isDiverse(int[][] arr2D) {
int[] sums = rowSums(arr2D); // Calculate row sums using rowSums method
// Check for duplicate sums
for (int i = 0; i < sums.length - 1; i++) {
for (int j = i + 1; j < sums.length; j++) {
if (sums[i] == sums[j]) {
return false;
}
}
}
return true;
}
// rowSums
method from earlier
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;
}
// arraySum method from earlier
public static int arraySum(int[] arr) {
int sum = 0;
for (int num : arr) { // iteration
sum += num;
}
return sum;
}
}
Main.main(null);
Output:
Company 1 is diverse: true
Company 2 is diverse: false
1c Explanation
I first declared and initialized two 2D arrays. These arrays, comp1
and comp2
, represent employee counts categorized by location and occupation for two different companies. The program then proceeds to test the isDiverse
method with these arrays. The isDiverse
method checks whether the provided 2D array is diverse, meaning each row’s sum is distinct from the sums of other rows. It does this by first calculating the sum of each row using the rowSums
method. Then, it checks for any duplicate sums among these row sums. If it finds any duplicates, it returns false, indicating that the array is not diverse. Otherwise, it returns true. The isDiverse
method is somewhat related to the KNN algorithm that our project group used for recommending jobs to potential applicants because it can detect which jobs are more or less competitive in different areas, which would feed into the layers of the KNN algorithm, making it more accurate at recommending jobs to potential applicants living in diverse geographical locations. The below method would be a potential place to input this change:
public static Worker findMostRelevantWorker(List<Worker> workers, Worker newWorker, int k)
{
Map<Double, Worker> distanceMap = new HashMap<>();
// Calculate Euclidean distance for each worker
for (Worker worker : workers) {
double distance = calculateDistance(worker, newWorker);
distanceMap.put(distance, worker);
}
// Sort distances and get the top k neighbors
List<Double> distances = new ArrayList<>(distanceMap.keySet());
Collections.sort(distances);
// Return the most relevant worker
return distanceMap.get(distances.get(0));
}