Question

Calculating prefix average of a set of values is an important problem, especially in financial calculations....

Calculating prefix average of a set of values is an important problem, especially in financial calculations. Use the following link to understand background on prefix averages problem - http://csfundamentals.com/tech-interview/dsa/prefix-averages-algorithm-java-program.php Consider the algorithms (methods) – prefixAverage1 and prefixAverage2 for calculating prefix averages. The source code is given to you. Implement both the algorithms and perform an experiment analysis of their running times under different input sizes. Visualize the running times on a chart, where x-axis represents different input sizes and y-axis represents running times of the algorithms.

Code:

package Assignment2;

/**
* Demonstration of algorithms for computing the prefix averages of an array.
*
* @author Michael T. Goodrich
* @author Roberto Tamassia
* @author Michael H. Goldwasser
*/
class PrefixAverage {

/** Returns an array a such that, for all j, a[j] equals the average of x[0], ..., x[j]. */
public static double[] prefixAverage1(double[] x) {
    int n = x.length;
    double[] a = new double[n];    // filled with zeros by default
    for (int j=0; j < n; j++) {
      double total = 0;            // begin computing x[0] + ... + x[j]
      for (int i=0; i <= j; i++)
        total += x[i];
      a[j] = total / (j+1);        // record the average
    }
    return a;
}

/** Returns an array a such that, for all j, a[j] equals the average of x[0], ..., x[j]. */
public static double[] prefixAverage2(double[] x) {
    int n = x.length;
    double[] a = new double[n];    // filled with zeros by default
    double total = 0;              // compute prefix sum as x[0] + x[1] + ...
    for (int j=0; j < n; j++) {
      total += x[j];               // update prefix sum to include x[j]
      a[j] = total / (j+1);        // compute average based on current sum
    }
    return a;
}

}

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

public class PrefixAverage {
        /**
         * Returns an array a such that, for all j, a[j] equals the average of x[0],
         * ..., x[j].
         */
        public static double[] prefixAverage1(double[] x) {
                int n = x.length;
                double[] a = new double[n]; // filled with zeros by default
                for (int j = 0; j < n; j++) {
                        double total = 0; // begin computing x[0] + ... + x[j]
                        for (int i = 0; i <= j; i++)
                                total += x[i];
                        a[j] = total / (j + 1); // record the average
                }
                return a;
        }

        /**
         * Returns an array a such that, for all j, a[j] equals the average of x[0],
         * ..., x[j].
         */
        public static double[] prefixAverage2(double[] x) {
                int n = x.length;
                double[] a = new double[n]; // filled with zeros by default
                double total = 0; // compute prefix sum as x[0] + x[1] + ...
                for (int j = 0; j < n; j++) {
                        total += x[j]; // update prefix sum to include x[j]
                        a[j] = total / (j + 1); // compute average based on current sum
                }
                return a;
        }
        
        public static double[] createRandomArray(int size) {
                double result[] = new double[size];
                
                for(int i=0; i<size; i++) {
                        result[i] = Math.random() * size;
                }
                
                return result;
        }
        
        public static void findTime(int size) {
                System.out.println("For Size: " + size);
                double data[] = createRandomArray(size);
                
                long start = System.currentTimeMillis();
                prefixAverage1(data);
                long end = System.currentTimeMillis();
                System.out.println("Prefix1 time: " + (end - start) + " ms");
                
                start = System.currentTimeMillis();
                prefixAverage2(data);
                end = System.currentTimeMillis();
                System.out.println("Prefix2 time: " + (end - start) + " ms\n");
        }
        
        public static void main(String args[]) {
                findTime(100);
                findTime(1000);
                findTime(10000);
                findTime(100000);
        }
}
**************************************************
The prefix1 Algorithm is an O(N^2) algorithm, Since it has nested loops.. in each iteration, it starts from First element and goes till ith Element, Due to which it is an O(N^2) algorithm
The Prefix2 algorithm is a linear O(N) algorithm, as it uses just one loop. It rebuilds the result by adding more data on previous calculation, hence it is optimized.


Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Add a comment
Know the answer?
Add Answer to:
Calculating prefix average of a set of values is an important problem, especially in financial calculations....
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
  • 8.         R-4.8 Order the following functions by asymptotic growth rate. 4nlogn + 2n 2^10    2^logn 3n...

    8.         R-4.8 Order the following functions by asymptotic growth rate. 4nlogn + 2n 2^10    2^logn 3n + 100logn      4n     2^n n^2 + 10n        n^3       nlogn 9.         R-4.9 Give a big-Oh characterization, in terms of n, of the running time of the example 1 method shown in Code Fragment 4.12. 10.       R-4.10 Give a big-Oh characterization, in terms of n, of the running time of the example 2 method shown in Code Fragment 4.12. 11.       R-4.11 Give a big-Oh characterization, in...

  • /*––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/ /*    */ /* */ /* This program computes average power, average magnitude */ /*...

    /*––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/ /*    */ /* */ /* This program computes average power, average magnitude */ /* and zero crossings from a speech signal. */ #include <stdio.h> #include <math.h> #define MAXIMUM 50 int main(void) { /* Declare variables */ int k=0, npts=30; double speech[MAXIMUM]={0.000000,-0.023438,-0.031250,-0.031250,-0.039063,-0.039063,-0.023438,0.000000,0.023438,0.070313,-0.039063,-0.039063,0.046875,0.101563,0.117188,0.101563,0.070313,0.054688,0.023438,0.000000,-0.031250,-0.039063,-0.070313,-0.070313,-0.070313,-0.070313,-0.062500,-0.046875,-0.039063,-0.031250}; /* Declare the function prototypes */    /* Compute and print statistics. */ printf("\n SPEECH DATA "); print(,,);//complete the statement printf("\n"); printf(" SPEECH STATISTICS : \n"); printf(" average power: %f \n",);//complete the statement printf(" average magnitude: %f...

  • Prove Big O in terms of nₒ and C? There are 5 examples: class Exercise {...

    Prove Big O in terms of nₒ and C? There are 5 examples: class Exercise { public static int example1(int[] arr) { int n = arr.length, total = 0; for (int j=0; j < n; j++) // loop from 0 to n-1 total += arr[j]; return total; } public static int example2(int[] arr) { int n = arr.length, total = 0; for (int j=0; j < n; j += 2) // note the increment of 2 total += arr[j]; return...

  • In the code shown above are two parts of two different exercises. HOW WE CAN HAVE...

    In the code shown above are two parts of two different exercises. HOW WE CAN HAVE BOTH OF THEM ON THE SAME CLASS BUT SO WE CAN RECALL them threw different methods. Thank you. 1-First exercise import java.util.Scanner; public class first { public static int average(int[] array){    int total = 0;    for(int x: array)        total += x;    return total / array.length;    } public static double average(double[] array){    double total = 0;    for(double x: array)        total += x;    return total /...

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

  • Suppose you have a sorted array of positive and negative integers and would like to determine...

    Suppose you have a sorted array of positive and negative integers and would like to determine if there exist some value of x such that both x and -x are in the array. Consider the following three algorithms: Algorithm #1: For each element in the array, do a sequential search to see if its negative is also in the array. Algorithm #2:For each element in the array, do a binary search to see if its negative is also in the...

  • 1) Write a script(in Bash shell) that characterizes the application performance. Specifically, your script should automatically...

    1) Write a script(in Bash shell) that characterizes the application performance. Specifically, your script should automatically test both algorithms of the matrix math program for each of the array sizes shown in Table. Also, extend your script to automatically parse the output of the program. Table (Array Sizes in Test Suite) Algorithm 1 Algorithm 2 256 256 512 512 768 768 1024 1024 1280 1280 1536 1536 1792 1792 2048 2048 C source file // Adapted from https://gustavus.edu/+max/courses/F2011/MCS-284/labs/lab3/ // Max...

  • Which of the following are valid array declarations? a. int[] array- new int[10]; b. double [array...

    Which of the following are valid array declarations? a. int[] array- new int[10]; b. double [array double[10]; c. charl charArray "Computer Science"; None of the above Analyze the following code: class Test public static void main(Stringl] args) System.out.println(xMethod(10); public static int xMethod(int n) System.out.println("int"); return n; public static long xMethod(long n) System.out.,println("long"); return n The program displays int followed by 10 The program displays long followed by 10. The program does not compile. None of the above. tions 3-4 are...

  • First create the two text file given below. Then complete the main that is given. There...

    First create the two text file given below. Then complete the main that is given. There are comments to help you. An output is also given You can assume that the file has numbers in it Create this text file: data.txt (remember blank line at end) Mickey 90 Minnie 85 Goofy 70 Pluto 75 Daisy 63 Donald 80 Create this text file: data0.txt (remember blank line at end) PeterPan 18 Wendy 32 Michael 28 John 21 Nana 12 Main #include...

  • hello there. can you please help me to complete this code. thank you. Lab #3 -...

    hello there. can you please help me to complete this code. thank you. Lab #3 - Classes/Constructors Part I - Fill in the missing parts of this code #include<iostream> #include<string> #include<fstream> using namespace std; class classGrades      {      public:            void printlist() const;            void inputGrades(ifstream &);            double returnAvg() const;            void setName(string);            void setNumStudents(int);            classGrades();            classGrades(int);      private:            int gradeList[30];            int numStudents;            string name;      }; int main() {          ...

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
ADVERTISEMENT
ADVERTISEMENT