I would like to make my code more implementable for other applications

49 views Asked by At

I would like to make my code more implementable for others applications.

I don't have problems with the code, it works perfectly. I would just like to rewrite it to use it in other contexts.

My original code:

import java.util.concurrent.*;  
 class Sum extends RecursiveTask<Double> { 
 final int seqThresHold = 500; 
 double[] data;  
 int start, end; 
 Sum(double[] vals, int s, int e ) { 
    data = vals; 
    start = s; 
    end = e; 
  } 
 protected Double compute() { 
    double sum = 0; 
 if((end - start) < seqThresHold) { 
      for(int i = start; i < end; i++) sum += data[i]; 
    } 
    else { 
      int middle = (start + end) / 2; 
 Sum subTaskA = new Sum(data, start, middle); 
      Sum subTaskB = new Sum(data, middle, end); 
 subTaskA.fork(); 
      subTaskB.fork(); 
 sum = subTaskA.join() + subTaskB.join(); 
    } 
      return sum; 
  } 
} 
 class RecurTaskDemo {  
  public static void main(String args[]) {  
    ForkJoinPool fjp = new ForkJoinPool(); 
 double[] nums = new double[5000]; 
 for(int i=0; i < nums.length; i++) 
      nums[i] = (double) (((i%2) == 0) ? i : -i) ; 
 Sum task = new Sum(nums, 0, nums.length); 
 double summation = fjp.invoke(task); 
 System.out.println("Summation " + summation); 
  }  
}

The new code I would like to get:

public class RecurTaskDemo {

    private static double Sum(double[] data, int start, int end) {
        double sum = 0;
        for (int i = start; i < end; i++) {
            sum += data[i];
        }
        return sum;
    }

    // ???

    public static void main(String args[]) {

        double[] nums = new double[4000];
        for (int i = 0; i < nums.length; i++)
            nums[i] = (double) (((i % 2) == 0) ? i : -i);

        double sum = Sum(nums, 0, 4000);

        // double sum = ... I would like to calculate 'sum' using 'Sum(...)' + '???'

        System.out.println(sum);

    }

}
0

There are 0 answers