Google Answers Logo
View Question
 
Q: Data Structure and Algorithm in Java ( Answered,   0 Comments )
Question  
Subject: Data Structure and Algorithm in Java
Category: Computers > Programming
Asked by: math01-ga
List Price: $20.00
Posted: 19 May 2003 05:54 PDT
Expires: 18 Jun 2003 05:54 PDT
Question ID: 205787
The solution I am seeking is for question 3. Questions 1 and 2 are
just to help you understand the problem.
 
1. Consider the following program for computing the cumulative sum of
a given list. An example of sample input and output from this program
is as follows:
Input list:   1  4  2  6  7  1  0  5 
 
Output list:  1  5  7  13 20 21 21 26 
 
Note that each number in the output list is the sum of all numbers up
to (and including) the current location in the input list.
Our first program segment for computing this is as follows: 
    for (i = 0; i < n; i++) 
        output_list[i] = 0; 
    for (i = 0; i < n; i++) 
        for (j = 0; j <= i; j++) 
            output_list[i] += input_list[j]; 
What is the runtime of this code segment in big-O notation?  
 
2. We write an alternate program for the same problem. In this case,
we notice that to compute output_list[i], you only need to add
input_list[i] and output_list[i-1].
The program segment is as follows: 
 for (i = 0; i < n; i++) 
 output_list[i] = 0; 
output_list[0] = input_list[0]; 
for (i = 1; i < n; i++) 
 output_list[i] = output_list[i-1]  
 + input_list[i]; 
What is the runtime of this code segment in big-O notation?  
 
3. Code the programs for computing cumulative sum of a list
(illustrated in Problems 1 and 2) in Java. Execute each of these
programs on lists of increasing sizes and note the runtime. Comment on
the growth rate of runtimes for the two programs
Answer  
Subject: Re: Data Structure and Algorithm in Java
Answered By: rhansenne-ga on 19 May 2003 07:30 PDT
 
Hi math01-ga,

Beneath you'll find a simple java program illustrating both kinds of
cumulative sums. I'll make the code available for download as well, as
the layout might change when posting this message.


The program calculates the cumulative sum in both ways on a number
list of increasing length and writes out the time it took to calculate
the sum (in milliseconds). The numbers of each list are generated
randomly. Only the short list (of 10 numbers) is printed to the
console, as printing 1000's of numbers to the console would be
confusing. As you'll see this time increases rapidly when using the
slow method and remains very low when using the fast method.


This is caused by the fact that the first method contains a nested
for-loop. Now look at the inner loop of the first method. You'll see
that the inner loop is traversed n-1 times, n-2 times, n-3 times ...
all the way down to one time. Put all together that is O(n-1)+ O(n-2)
+ O(n-3) + ... + O(1).  There are n-1 terms here, and each is no worse
than O(n), so clearly the total is no worse than O((n-1)*n) = O(nē),
but many of the terms are much smaller than n, so we should be more
careful. Now, the sum 1 + 2 + 3 + ... + n = n(n+1)/2 = O(nē).  Note
that we are interested in  O(n-1)+ O(n-2) + O(n-3) + ... + O(1) =
O((n-1)+ (n-2) + (n-3) + ... + (1)), which is just the same as the sum
of 1 through n backwards, except we leave off the biggest term n, so
O(n-1)+ O(n-2) + O(n-3) + ... + O(1) = O(nē - n) = O(nē).


The fast method does not use a nested loop and therefore executes in a
runtime of O(n).


You can compile the code from the command line using: "javac
CumulativeSum.java"
and execute the program using: "java CumulativeSum"

I assume you know how to compile and run the program, but if you run
into any problem, just let me know and I'll do my best to assist.

The program:
--------------------------------------------------


public class CumulativeSum {


  public static void main(String[] args) {

    System.out.println("CUMULATIVE SUM WITH METHOD 1:");
    // the first parameter determines the length of the list
    // the second parameter (true/false) indicates whether or not the
list of numbers should be printed
    slowCumulativeSum(getRandomIntArray(10),true);
    slowCumulativeSum(getRandomIntArray(10000),false);
    slowCumulativeSum(getRandomIntArray(20000),false);
    slowCumulativeSum(getRandomIntArray(30000),false);
    slowCumulativeSum(getRandomIntArray(40000),false);
    slowCumulativeSum(getRandomIntArray(50000),false);

    System.out.println("CUMULATIVE SUM WITH METHOD 2:");
    slowCumulativeSum(getRandomIntArray(10),true);
    fastCumulativeSum(getRandomIntArray(10000),false);
    fastCumulativeSum(getRandomIntArray(20000),false);
    fastCumulativeSum(getRandomIntArray(30000),false);
    fastCumulativeSum(getRandomIntArray(40000),false);
    fastCumulativeSum(getRandomIntArray(50000),false);
    fastCumulativeSum(getRandomIntArray(100000),false);
    fastCumulativeSum(getRandomIntArray(1000000),false);
  }

  /**
   * Calculates the cumulative sum of a list of integer numbers using
   * the slow method
   *
   * @param input_list A list of numbers
   * @param print true if the input and output lists should be printed
to the console
   */
  private static void slowCumulativeSum(int[] input_list, boolean
print) {
    System.out.println("calculating cumulative sum for input list
length "+input_list.length+")...");

    if (print) printList(input_list);

    int output_list[] = new int[input_list.length];
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < input_list.length; i++)
            for (int j = 0; j <= i; j++)
                output_list[i] += input_list[j];
    long endTime = System.currentTimeMillis();

    if (print) printList(output_list);

    System.out.println("runtime: "+(endTime-startTime)+"ms.");

  }

  /**
   * Calculates the cumulative sum of a list of integer numbers using
   * the fast method
   *
   * @param input_list A list of numbers
   * @param print true if the input and output lists should be printed
to the console
   */
  private static void fastCumulativeSum(int[] input_list, boolean
print) {
    System.out.println("calculating cumulative sum for input list
length "+input_list.length+")...");

    if (print) printList(input_list);

    int output_list[] = new int[input_list.length];
    long startTime = System.currentTimeMillis();
    for (int i = 1; i < input_list.length; i++)
         output_list[i] = output_list[i-1] + input_list[i];
    long endTime = System.currentTimeMillis();

    if (print) printList(output_list);

    System.out.println("runtime: "+(endTime-startTime)+"ms.");

  }

  /**
   * Returns a random integer array with elements in [0-9]
   *
   * @param length The length of the array
   */
  private static int[] getRandomIntArray(int length) {
    int[] list = new int[length];
    for (int i=0;i<length;i++) list[i] = getRandomInt();
    return list;
  }

  /**
   * Returns a random integer in [0-9]
   */
  private static int getRandomInt() {
    return (int) (Math.random()*10);
  }


  /**
   * Prints a list of numbers to the console
   */
  private static void printList(int[] list) {
    for (int i = 0; i < list.length; i++)
      System.out.print(list[i]+" ");
    System.out.println();
  }
}


--------------------------------------------------

The output of the program on my PC:



CUMULATIVE SUM WITH METHOD 1:

calculating cumulative sum for input list length 10000)...

runtime: 625ms.

calculating cumulative sum for input list length 20000)...

runtime: 1890ms.

calculating cumulative sum for input list length 30000)...

runtime: 3516ms.

calculating cumulative sum for input list length 40000)...

runtime: 6000ms.

calculating cumulative sum for input list length 50000)...

runtime: 9562ms.

CUMULATIVE SUM WITH METHOD 2:

calculating cumulative sum for input list length 10000)...

runtime: 0ms.

calculating cumulative sum for input list length 20000)...

runtime: 0ms.

calculating cumulative sum for input list length 30000)...

runtime: 0ms.

calculating cumulative sum for input list length 40000)...

runtime: 0ms.

calculating cumulative sum for input list length 50000)...

runtime: 0ms.

calculating cumulative sum for input list length 100000)...

runtime: 2ms.

calculating cumulative sum for input list length 1000000)...

runtime: 62ms.




Depending on the speed of your processor, the times might differ
significantly, however it should still remain obvious that the second
method is much faster than the first. Feel free to experiment with the
lengths.

Hope this helps!

Kind regards,

rhansenne-ga.

Clarification of Answer by rhansenne-ga on 19 May 2003 07:33 PDT
You can download the source code and compiled code from:

http://users.pandora.be/rami/temp

Best regards,

rhansenne-ga.

Request for Answer Clarification by math01-ga on 19 May 2003 11:23 PDT
Hi rhansenne-ga,
I compiled and ran the program but keep getting the error message:
"There is an error launching the java program".

Please advise.

Clarification of Answer by rhansenne-ga on 19 May 2003 13:58 PDT
Hi,

I tried to run the class again and it works without problems on both a
Windows and Linux machine. If you copied the code on this page, the
formatting might produce errors. Use the original code in stead:

http://users.pandora.be/rami/temp/CumulativeSum.java

and the compiled version:

http://users.pandora.be/rami/temp/CumulativeSum.class

You can run the last file from the command line by typing "java
CumulativeSum" from the directory where the file is located.

If you still have problems running the program, could you provide the
exact/full error message you receive, as well as a detailed
description of the way you started the program?

Good luck!

Request for Answer Clarification by math01-ga on 25 May 2003 10:36 PDT
Hi rhansenne-ga,

Which import class did you use to execute the program?

Clarification of Answer by rhansenne-ga on 26 May 2003 03:14 PDT
Hi math01-ga,

This class doesn't need any additionnal import classes. It should run
fine by itself. Have you tried running the program from the command
line as "java
CumulativeSum" in the same directory as the "CumulativeSum.class"
file? If so, can you provide me with the returned message or error?

Make sure a recent virtual machine is installed on your system
(preferably J2SE 1.4 or later, which you can download from
http://java.sun.com/j2se/1.4.1/download.html). I'm assuming you are
running the examples on a Windows environment. If you are using Linux
or another operating system, please let me know (the program should
still work though). Also make sure the following system variables are
set:

JAVA_HOME which should refer to your java home directory, for example
"C:\j2sdk1.4.1_01".

PATH which should refer to the bin directory of your java home, for
example "C:\j2sdk1.4.1_01\bin".

More information and examples on setting these variables and
running/compiling a java program can be found here:
http://www.cs.armstrong.edu/liang/intro4e/JDKonDOS.pdf

Hope this helps,

rhansenne-ga
Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy