/**
Iluustration of RecursiveTask
*/
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class SumWithPool{
public static void main(String[] args) throws InterruptedException,
ExecutionException {
//get the number of avaialbe CPUs
int nThreads = Runtime.getRuntime().availableProcessors();
System.out.println("Available CPUs: " + nThreads);
//create an array of data
int n = 10; //initital data size
if(args.length > 0) // use the user given data size
n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for(int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
ForkJoinPool forkJoinPool = new ForkJoinPool(nThreads);
Sum s = new Sum(numbers,0,numbers.length);
long startTime = System.currentTimeMillis(); //start timer
Long result = forkJoinPool.invoke(s);
long endTime = System.currentTimeMillis();
long timeElapsed = endTime - startTime;
System.out.println("Concurrent executing time: " + timeElapsed + "ms");
System.out.println("The conccurent sum: " + result);
//redo the task sequentially
startTime = System.currentTimeMillis(); //start timer
result = sum(numbers);
endTime = System.currentTimeMillis();
timeElapsed = endTime - startTime;
System.out.println("\nSequential executing time: " + timeElapsed + "ms");
System.out.println("The sequential sum: " + result);
}
/** sequential sum */
private static long sum(int[] arr){
long sum = 0;
for(int i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
}
}
/** create a class that handle a task */
class Sum extends RecursiveTask<Long> {
private int low;
private int high;
private int[] array; //only reference to the given data
/** map the attribute to the given data */
public Sum(int[] array, int low, int high) {
this.array = array;
this.low = low;
this.high = high;
}
/** overriding tehe comput method */
protected Long compute() {
if(high - low <= 10) { //do the sum if the block of data is managable
long sum = 0;
for(int i = low; i < high; ++i)
sum += array[i];
return sum;
} else {
int mid = low + (high - low) / 2;
Sum left = new Sum(array, low, mid);
Sum right = new Sum(array, mid, high);
left.fork();
long rightResult = right.compute();
long leftResult = left.join();
return leftResult + rightResult;
}
}
}
Trending nowThis is a popular solution!
Step by stepSolved in 5 steps with 6 images
- Write code in Java: - Code must be recursive. import java.util.*; import java.lang.*; import java.io.*; class BinaryToDecimal { // *More methods can be added* public static int binaryToDecimal(String binaryString) { // *Code goes here* } } class DriverMain { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print(BinaryToDecimal.binaryToDecimal(input.nextLine())); } }arrow_forwardWrite a recursive method called reverseString() that takes in a string as a parameter and returns the string in reversed order. The main method is provided to read a string from the user and call the reverseString() method. Ex: If the input of the program is: Hello the reverseString() method returns and the program outputs: Reverse of "Hello" is "olleH". Ex: If the input of the program is: Hello world! the reverseString() method returns and the program outputs: Reverse of "Hello, world!" is "!dlrow, olleH". Hint: Move the first character to the end of the returning string and pass the remaining sub-string to the next reverseString() method call.arrow_forwardIn java if i have this pseudo code that tries to explain how a method will work using recursion how can i turn this into working java codearrow_forward
- In java pls! here is some starter code for this problem: public class ThreadingDivisors { public static void main(String[] args) { long start = System.currentTimeMillis(); int maxDivisors = 0; int answer = 0; for (int n=1; n<100000; n++) { int divisors = getNumDivisors(n); if (divisors > maxDivisors) { maxDivisors = divisors; answer = n; } } System.out.println(answer + " has the most divisors (" + maxDivisors + ")"); long end = System.currentTimeMillis(); System.out.println(end - start + " milliseconds"); } public static int getNumDivisors(int n) { int numDivisors = 0; for (int i=1; i<=n; i++) { if (n % i == 0) { numDivisors++; } } return numDivisors; } }arrow_forwardInfoProcessorTest.java import java.util.*; /** * * Class to process and extract information from a list of lines. * */ public class InfoProcessorTest { /** * * List of lines to process. * */ private ArrayList<String> lines =new ArrayList<String>(); /** * * Creates InfoProcessor with given list of lines. * * @param lines to process * */ public InfoProcessorTest(ArrayList<String> lines) { this.lines = lines; } /** * * Gets the course name from the list of lines. * * First, finds the line that starts with "Course:". * * Second, gets the String on the very next line, which should be the course * name. * * Third, returns the String from the method. * * * * Hint(s): * * - Use the getNextStringStartsWith(String str) method to find the course name * * * * Example(s): * * - If the ArrayList<String> lines contains: "Course:" and "CIT590", and we * call * * getCourseName(), we'll get "CIT590". * * * * - If the ArrayList<String> lines contains: "Course:"…arrow_forwardimport java.util.Arrays; import java.util.Random; public class Board { /** * Construct a puzzle board by beginning with a solved board and then * making a number of random moves. That some of the possible moves * don't actually change what the board looks like. * * @param moves the number of moves to make when generating the board. */ public Board(int moves) { throw new RuntimeException("Not implemented"); } The board is 5 X 5. You can add classes and imports like rand.arrow_forward
- RPN.java import java.util.Scanner; /** * Reverse Polish Notation calculator. It evaluates * a string with expressions in RPN format and prints * the results. Exampel of a stack use. */public class RPN{ /** * Given a string, return an integer version of * the string. Check if the string contains only * numbers, if so, then does the conversion. If * it does not, it reurns 0. * @param t string with numeric token * @return int version of the numeric token in t */ public int getValue(String t) { if (t.matches("[0-9]+")) { return Integer.parseInt(t); } else { return 0; } } /** * Evaluates a single token in an RPN expression. If it is * a number, it pushes the token to the stack. If it is an * operator, then it pulls 2 numbers from the stack, performs * the operation and pushes back into the stack the result. * @param token to be evaluated * @param stack holding values for…arrow_forwardWrite a Java method using recursion that reorders an integer array in such a way that all the even values comes before the odd values Here is the code to start, fill in the missing part output should be 8 6 2 4 4 4 4 3 5 5 3 7 1 9arrow_forwardGiven string inputStr on one line and integers idx1 and idx2 on a second line, output "Match found" if the character at index idx1 of inputStr is equal to the character at index idx2. Otherwise, output "Match not found". End with a newline. Ex: If the input is: eerie 4 1 then the output is: Match found Note: Assume the length of string inputStr is greater than or equal to both idx1 and idx2.arrow_forward
- Write a java class named First_Last_Recursive_Merge_Sort that implements the recursive algorithm for Merge Sort. You can use the structure below for your implementation. public class First_Last_Recursive_Merge_Sort { //This can be used to test your implementation. public static void main(String[] args) { final String[] items = {"Zeke", "Bob", "Ali", "John", "Jody", "Jamie", "Bill", "Rob", "Zeke", "Clayton"}; display(items, items.length - 1); mergeSort(items, 0, items.length - 1); display(items, items.length - 1); } private static <T extends Comparable<? super T>> void mergeSort(T[] a, int first, int last) { //<Your implementation of the recursive algorithm for Merge Sort should go here> } // end mergeSort private static <T extends Comparable<? super T>> void merge(T[] a, T[] tempArray, int first, int mid, int last) { //<Your implementation of the merge algorithm should go here> } // end merge //Just a quick method to display the whole array. public…arrow_forwardUsing Java.arrow_forwardStringFun.java import java.util.Scanner; // Needed for the Scanner class 2 3 /** Add a class comment and @tags 4 5 */ 6 7 public class StringFun { /** * @param args not used 8 9 10 11 12 public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter your first name: "); 13 14 15 16 17 18 System.out.print("Please enter your last name: "); 19 20 21 //Output the welcome message with name 22 23 24 //Output the length of the name 25 26 27 //Output the username 28 29 30 //Output the initials 31 32 33 //Find and output the first name with switched characters 34 //All Done! } } 35 36 37arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education