Question

Need some help on homework practice problems, Thank you in advance! Problem 1: Write a method,...

Need some help on homework practice problems, Thank you in advance!

Problem 1:

Write a method, parallelSum(), that uses the fork-join framework to compute the sum of the elements of an array. Its skeleton as well as its Javadoc is provided in the file ParallelSum.java. Simple code for testing and timing your method is also provided in the main method.

This problem is essentially the same as ParallelMax in structure. Therefore, follow the code for ParallelMax to complete ParallelSum.


Problem 2:

We again revisit the vote count problem you saw in Homework Assignments 1 and 8 as well as in the lecture. This time you are not required to sort the players by votes, but will count the votes in parallel using the fork-join framework and thread synchronization with a lock.

For the NBA All-Star Game, the fans vote for their favorite players. All the votes are stored in an array list, in which the name of a player appears once every time he receives a vote. A software expert, you are hired by the Commissioner to write an app that helps decide the starting lineups of the game. Write a method parallelVoteCount() that on the input array list of votes, returns a hash map that counts the number of votes each player receives. That is, each key of the map is the name of a player, and its associated value is the number of votes the player receives. The skeleton of parallelVoteCount() as well as its Javadoc, and the code for sequentialVoteCount(), the sequential method for counting votes, are provided in the file CountVotesInParallel.java. Simple code for testing and timing your method is also provided in the main method.

Even though this problem is different from other problems you have seen in this unit, except for thread synchronization the structure of the code for this problem is similar to that of RandomAssign and ParallelMergeSort. I therefore suggest that you reference their code while completing the code for this problem. For your convenience and the ease of my grading, I outline below the steps for the code. You must follow these steps to complete the method:

1. Create a RecursiveAction class CountTask to support parallelVoteCount().

2. Create the following private instance variables for the CountTask class:

2

 globalMap: A static hash map1 instance variable mapping strings to integers. This map will eventually contain the vote counts for all players.

 lock: A static reentrant lock instance variable

 THRESHOLD: A final static int instance variable. If the assigned sublist of votes has length below the threshold, then the task is to be executed sequentially.

 votes: An array list of strings that holds the votes

 low: The inclusive low index of the sublist assigned to the task

 high: The exclusive high index of the sublist assigned to the task

3. Write a constructor for CountTask that takes a list of votes, a low index and a high index as parameters and sets the corresponding instance variables properly.

4. Override the compute() method for CountTask as follows.

 If the sublist of votes assigned to the task as determined by low and high has length below THRESHOLD, then i. Use a local hash map localMap to count the votes in the sublist ii. Acquire the lock iii. Iterate through the entry set of localMap. For each key in the entry set, increment its value in globalMap by its value in localMap. iv. Release the lock

 Otherwise i. Divide the sublist into two (almost) equal halves ii. Recurse on the two halves in parallel using the invokeAll() method

5. Now complete the parallelVoteCount() method as follows:  Create a CountTask object representing the main task to solve  Create a fork-join pool of threads to execute the main task  Have the pool execute the main task by using the invoke() method  Finally return CountTask.globalMap

Sample code:

package hw9;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class CountVotesInParallel {

   public static void main(String[] args) {
       ArrayList<String> fav = new ArrayList<>();
       fav.add("LeBron");
       fav.add("Steph");
       fav.add("Luka");
       fav.add("Anthony");
       fav.add("Kawhi");
       fav.add("Giannis");
      
       int n = 10;
       ArrayList<String> votes = new ArrayList<>();
       for (int i = 0; i < n; i++) {
           int j = (int) (Math.random() * fav.size());
           votes.add(fav.get(j));
       }
       System.out.println(votes);
       System.out.println();
      
       long tic = System.currentTimeMillis();
       System.out.println("Sequential Count: " + sequentialVoteCount(votes));
       long toc = System.currentTimeMillis();
       System.out.println("Sequential time: " + (toc - tic) + " milliseconds");
       System.out.println();
      
       tic = System.currentTimeMillis();
       System.out.println("Parallel Count: " + parallelVoteCount(votes));
       toc = System.currentTimeMillis();
       System.out.printf("Parallel time with %d processors: %d milliseconds\n", Runtime.getRuntime().availableProcessors(), toc - tic);
       System.out.println();
      
   }
  
  
   /**
   * Sequential method for counting the number of votes for each player
   *
   * @param votes an array list of strings representing the names of players receiving votes
   * @return a hash map that counts the number of votes each player receives;
   * each key is the name of a player receiving votes, and its associated value
   * is the number of votes the player receives
   */
   public static HashMap<String, Integer> sequentialVoteCount(ArrayList<String> votes) {
       HashMap<String, Integer> map = new HashMap<>();
       for (String p : votes) {
           int count = map.getOrDefault(p, 0);
           map.put(p, count+1);
       }
      
       return map;
   }
  
  
   /**
   * Graded method for HW9 Problem 2
   *
   * Parallel method for counting the number of votes for each player
   * using fork-join and thread synchronization
   *
   * @param votes an array list of strings representing the names of players receiving votes
   * @return a hash map that counts the number of votes each player receives;
   * each key is the name of a player receiving votes, and its associated value
   * is the number of votes the player receives
   */
   public static HashMap<String, Integer> parallelVoteCount(ArrayList<String> votes) {
      
       // Replace this line with your return statement
       return null;
   }
  
  
   /*
   * Your static RecursiveAction class to support parallelVoteCount()
   * Name it CountTask
   */
  

}

Sample code 2:

package hw9;

import java.util.*;

public class ParallelSum {

   public static void main(String[] args) {
       int n = 10;
       double[] A = new double[n];
       Random rand = new Random();
       for (int i = 0; i < n; i++) {
           A[i] = Math.round(rand.nextDouble() * 10) / 10.0;
       }
       System.out.println("A: " + Arrays.toString(A));
       System.out.println();
      
       long tic = System.currentTimeMillis();
       System.out.println("Sequential Sum: " + sequentialSum(A));
       long toc = System.currentTimeMillis();
       System.out.println("Sequential time: " + (toc - tic) + " milliseconds");
       System.out.println();
      
       tic = System.currentTimeMillis();
       System.out.println("Parallel Sum: " + parallelSum(A));
       toc = System.currentTimeMillis();
       System.out.printf("Parallel time with %d processors: %d milliseconds\n", Runtime.getRuntime().availableProcessors(), toc - tic);
       System.out.println();
      
   }
  
  
   /**
   * Computes and returns the sum of the elements of a given array
   *
   * @param A an array of doubles
   * @return the sum of the elements of A
   */
   public static double sequentialSum(double[] A) {
       double sum = 0;
       for (int i = 0; i < A.length; i++) {
           sum += A[i];
       }
       return sum;
   }
  
  
   /**
   * Graded method for HW9 Problem 1
   *
   * Computes in parallel the sum of the elements of a given array
   * using the fork-join framework
   *
   * @param A an array of doubles
   * @return the sum of the elements of A
   */
   public static double parallelSum(double[] A) {
      
       // Replace this line with your return statement
       return -1;
   }
  
  
   /**
   * Your static RecursiveTask class to support parallelSum()
   * Name it SumTask
   */

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey, I have attached the code below. In the code I have added comments for explanation wherever necessary. If you have any doubts, let me know in the comment.

CountVotesInParallel.java:

package hw9;

import java.util.*;

import java.util.concurrent.*;

import java.util.concurrent.locks.*;

public class CountVotesInParallel {

public static void main(String[] args) {

ArrayList<String> fav = new ArrayList<>();

fav.add("LeBron");

fav.add("Steph");

fav.add("Luka");

fav.add("Anthony");

fav.add("Kawhi");

fav.add("Giannis");

int n = 10;

ArrayList<String> votes = new ArrayList<>();

for (int i = 0; i < n; i++) {

int j = (int) (Math.random() * fav.size());

votes.add(fav.get(j));

}

System.out.println(votes);

System.out.println();

long tic = System.currentTimeMillis();

System.out.println("Sequential Count: " + sequentialVoteCount(votes));

long toc = System.currentTimeMillis();

System.out.println("Sequential time: " + (toc - tic) + " milliseconds");

System.out.println();

tic = System.currentTimeMillis();

System.out.println("Parallel Count: " + parallelVoteCount(votes));

toc = System.currentTimeMillis();

System.out.printf("Parallel time with %d processors: %d milliseconds\n", Runtime.getRuntime().availableProcessors(), toc - tic);

System.out.println();

}

/**

* Sequential method for counting the number of votes for each player

*

* @param votes an array list of strings representing the names of players receiving votes

* @return a hash map that counts the number of votes each player receives;

* each key is the name of a player receiving votes, and its associated value

* is the number of votes the player receives

*/

public static HashMap<String, Integer> sequentialVoteCount(ArrayList<String> votes) {

HashMap<String, Integer> map = new HashMap<>();

for (String p : votes) {

int count = map.getOrDefault(p, 0);

map.put(p, count+1);

}

return map;

}

/**

* Graded method for HW9 Problem 2

*

* Parallel method for counting the number of votes for each player

* using fork-join and thread synchronization

*

* @param votes an array list of strings representing the names of players receiving votes

* @return a hash map that counts the number of votes each player receives;

* each key is the name of a player receiving votes, and its associated value

* is the number of votes the player receives

*/

public static HashMap<String, Integer> parallelVoteCount(ArrayList<String> votes) {

//create a ForkJoinPool object. A ForkJoinPool is an ExecutorService for running ForkJoinTasks

//in our case Recurive Tasks.

ForkJoinPool pool = new ForkJoinPool();

//create a recursiveaction class object

CountTask task = new CountTask(votes, 0, votes.size() - 1);

//execute the task and wait till the task is finished

pool.invoke(task);

//return the result

return task.map;

}

/*

* Your static RecursiveAction class to support parallelVoteCount()

* Name it CountTask

*/

static class CountTask extends RecursiveAction{

//variables

ArrayList<String> votes;

static HashMap<String, Integer> map = new HashMap<>(); //stores the result

int start, end;

//constructor

CountTask(ArrayList<String> votes , int start , int end){

this.votes = votes;

this.start = start;

this.end = end;

}

@Override

protected void compute(){

//this block will execute

//if this is only element

if(start == end){

//get the string

String p = votes.get(start);

int count = map.getOrDefault(p, 0);

map.put(p, count+1);

}

else if(end > start){

//split the task in two partitions

int mid = (start + end) / 2;

CountTask left = new CountTask(votes , start , mid);

CountTask right = new CountTask(votes , mid + 1, end);

//execute task

left.fork();

right.fork();

//join the tasks

left.join();

right.join();

}

}

}

}

Code Screenshots:

Output:

Add a comment
Know the answer?
Add Answer to:
Need some help on homework practice problems, Thank you in advance! Problem 1: Write a method,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert a...

    2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a hashtable For every element in array: counter0 a. b. c. .Look for array[i] . Look for array [幻 + k in the hash map, if found then increment counter. -k in the hash map, if found then increment counter. Remove arrayli] from hash table. d. return counter For example: Input : array[] {1, 5, 3, 4, 2), k 3 Output:...

  • I need to program 3 and add to program 2 bellows: Add the merge sort and...

    I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....

  • Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating...

    Write a method public static ArrayList merge(ArrayList a, ArrayList b) that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For example, if a is 1 4 9 16 and b is 9 7 4 9 11 then merge returns the array list 1 9 4 7 9 4 16 9 11...

  • Write a method called printReverse() that takes a string and uses recursion to print the contents...

    Write a method called printReverse() that takes a string and uses recursion to print the contents of the string in reverse order. The string itself should not be reversed; it must be left in its original form. The method has the following header:   void printReverse(String s, int i) where s is a reference to the string, and i is an integer parameter that you may use as you see fit. You do not need to code up this method as...

  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Hi everyone! I need help on my Java assignment. I need to create a method that...

    Hi everyone! I need help on my Java assignment. I need to create a method that is called sumIt that will sum two values and will return the value.It should also invoke cubeIt from the sum of the two values. I need to change the currecnt program that I have to make it input two values from the console. The method has to be called sumIt and will return to the sum that will produce the cube of the sum...

  • Problem 2 Using the Album and Music StoreDemo from problem 1, write a method to find...

    Problem 2 Using the Album and Music StoreDemo from problem 1, write a method to find all of the albums that are cheaper than a specific price In the MusicStoreDemo, add a new method called getAlbumsCheaperThan. The method passes in the ArrayList of albums and the price. The method will return an ArrayList of all albums cheaper than the price passed in. Update the main method in the Music Store Demo and have it find all of the albums that...

  • Problem 1 Given a linked list of integers, write a function getUnique that removes all duplicates elements in the linked list and returns the new linked list of unique elements (The order does not ma...

    Problem 1 Given a linked list of integers, write a function getUnique that removes all duplicates elements in the linked list and returns the new linked list of unique elements (The order does not matter). Example: Input: 1-»2->3->1-2 Output: 1->2->3 public class Node f int iterm Node next; Node(int d) t item = d; next-null; ) import java.util.ArrayList; public class ExtraLab public static void main (String[] args)t PROBLEM 1 System.out.println("PROBLEM 1"); Node head new Node(1); head.next-new Node (2); head.next.next-new Node(3);...

  • Objective: in Java Write a program that implements 3 sorting algorithms and times them in real ti...

    Objective: in Java Write a program that implements 3 sorting algorithms and times them in real time. These algorithms will sort Cylinders by their volume. First, download the driver and include it in your project. Write a class Cylinder with the following properties baseRadius: a non-negative number that corresponds to the Cylinder’s base’s radius. height: a non-negative number that corresponds to the Cylinder’s height. Next, write a class Sorter with the following bubbleSort: This static method takes in an array...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
Active Questions
ADVERTISEMENT