Homework 06



Due: 11:59 PM on Friday, October 15, 2004

3 problems, worth 10, 20, and 20 points, respectively (plus ex. cr. of up to 20%)

Problem 1 (10 points)     the Morning Meander     [topic: using loops and methods]

In this problem, you will create a simple ASCII animation that represents a tired student's trek from the dining hall to either the east or west side of campus. You may want to refer to the example and notes we went over in class to help with this.

Output: Your program should represent the student by an ASCII character (a visible, printable one!) of your choice. It should also somehow indicate the endpoints of the student's path. The example below uses vertical bars '|' to do this. You should ask the user for the width of the path (the distance from the center to the path's edge).

When run, the program should continually output lines of text displaying the position of the student on the path. Each line should show the random "step" of the student left or right, until she is adjacent to one or the other end, at which point the program stops. At the end, the program should print out the total number of steps taken during its run.

Example Run: Here is an example run. The student in this case randomly stays still, moves left or moves right. The S character represents the student, while the vertical bar | characters represent the end of the path:


How wide would you like your path?   24

    |                        S                        |
    |                        S                        |
    |                       S                         |
    |                        S                        |
    |                       S                         |
    |                        S                        |
    |                        S                        |
    |                       S                         |
    |                        S                        |
    |                         S                       |
    |                         S                       |
    |                        S                        |
    |                       S                         |
    |                        S                        |
    
               < many lines skipped... >               
    
    |  S                                              |
    |   S                                             |
    |    S                                            |
    |    S                                            |
    |    S                                            |
    |    S                                            |
    |   S                                             |
    |  S                                              |
    |   S                                             |
    |  S                                              |
    |  S                                              |
    |   S                                             |   
    |   S                                             |
    |  S                                              |
    |  S                                              |
    |   S                                             |
    |  S                                              |
    | S                                               |
    |S                                                |


The student took 996 steps.

Method to write For this problem, you should write a method


    public static void printLine(int w, int p)
that prints a single line of the student's wander. The input variable p represents the position of the student. The variable w represents the distance from the center of the path to either edge. The end of the path should be one space past w, and w (or -w) is where the wandering student should stop.

Hint on drawing One way to draw a single line of output is with a for loop, in which i runs from -w to w. Outside this for loop would be the characters that mark either end of the path. Inside the for loop you might want to print one character per loop -- an if statement is a good method for deciding which character to print.

Extra Credit For extra credit (of up to 10%), improve this simple ASCII animation according to your own tastes. For example, you may want to have more than one person wandering; you may have the wanderers "bounce off" each other or annihilate each other -- creativity is welcome!






Problem 2 (20 points)     throwing darts at pi     [topic: using loops and methods]

In this problem you will write a program to compute pi (3.14159...). This problem will revisit the idea of Monte Carlo methods used in the Monte Hall program of HW4, this time using a geometric metaphor.

main method:

Your main method should offer the user a choice of two options, for example, as follows:

      Welcome to the pi estimator. You may
        (0) Decide how many darts to throw
        (1) Throw darts to estimate pi to a certain accuracy
        (9) Quit
    
      Which would you like to try?  
There are two more options available for extra credit -- see the bottom of this assignment for details on them.

Choice 0

If the user chooses 0, the following is an example of an appropriate interaction (with user input in blue):
      Enter an integer number of darts you would like to throw  100000
    
      Total throws:    100000
      Total hits:      78371
      Estimate of PI:  3.13484
    
      < the original menu prints out again >
  
Thus, for option 0 your program should prompt for an integer number of darts to use. (You may assume this will be a positive integer.) Then, you should "throw" that many darts at a square dartboard spanning from -1 to 1 in both x and y. In essence, this means generating a random point (x,y) with -1 <= x < 1 and -1 <= y < 1.

For each dart "thrown," determine whether it landed within the circle of radius 1 centered at the point (0, 0). Your program should count the number of times it hits this circle.

With a dart thrown randomly into the enclosing square, the chances of hitting the circle is pi/4. As a result, you can estimate pi by

  4.0 * ( number of hits ) / ( number of darts )
After throwing the desired number of darts, the program should print the total number thrown, the total number of "hits," and the resulting estimate of pi.

Choice 1

If the user chooses number 1 (from the menu in main), the following is (approximately) what your program should do (feel free to personalize, if you wish):
      Enter a positive tolerance (< 1.0)  0.0000001
    
      Total throws:   34119
      Total hits:     26797

      The resulting estimate of pi is 3.1415926609806855
          The "actual" value of pi is 3.141592653589793
    
      < the main menu would appear again here >
  
That is, for option 1 your program should prompt for a tolerance within which you want to estimate pi. This will be a double, and you can assume it will be strictly positive and less than 1.

Your program should then "throw darts" in the same way it does for choice 0, determining whether or not each dart hits the circle. Each time, however, the program should compute a new estimate of pi using the formula mentioned above. It should continue until the estimated value of pi is within the user-specified tolerance of the actual value of pi.

You should use Java's built-in value Math.PI as the "actual" value of pi.

After the program has estimated pi within the desired tolerance, it should print out this estimate, the "true" value of pi (Math.PI), as well as the total number of darts needed and the total number of darts that hit the inner circle. This part is really a test of how much work Monte Carlo estimation requires to achieve a particular level of accuracy.

Other choices

If the user types in anything other than a 0 or a 1, the program should remind the user of the possible options and then proceed to the "finishing up" section, below. Option 9 should quit the program.

Methods to write

Yes, it is possible to write this program with no external methods. However, in order to practice using a method that returns a boolean value, for this problem you should write the following method (and use it to help implement choices 0 and 1):

Be sure to submit your CS5App.java file under homework 6, problem 2.






Problem 3 (20 points)     A program that "reads" ...     [topic: looping, methods, Strings, and chars]



Pair Programming Problem



You have the option of working in a pair on this problem. As with previous weeks, you should make sure that your pair works together throughout the problem, and that each partner "drives" and each "advises" about half the time.

The problem     The Flesch index is a measure of the readability of a particular text. It is often used by textbook publishers and editors to ensure that material is written at a level appropriate for the intended audience. If you're interested in several different numeric measures of readability, there is quite a complete explanation here.

The Flesch index is computed as follows:

Here are some resulting readability scores for a few example publications or styles of writing (cited from Cay Horstmann's book, p. 266). It is, in fact, possible to have a negative readability score:

This problem asks you to compute the Flesch readability score for text that is read in from a file. In order to do this, you should start from the skeleton code provided:

    public static void main(String[] args)
    {
        H.inputFromFile("../testfile.txt");   // this is the file in Hw6Pr3 being read in
                                              // you may copy ANY text to this file...
        
        while (true)                  // loop indefinitely
        {
            String w1 = H.nw();       // get one "word" from the file
	          H.pl("w1 is " + w1);      // you will want to remove this eventually
            
            if (w1.equals("END"))     // if the word END is encountered, we quit the loop
                break;
            
            String w2 = dePunct(w1);  // this line removes punctuation from w1
            H.pl("w2 is " + w2);      // you will want to remove this eventually
        }
    }

The above code demonstrates how to get word-by-word input from a file (and you can put anything you like in that file) and it also demonstrates a method that is provided for removing punctuation (dePunct). You should try this program out with different text in the file testfile.txt to see how it works. Notice that the loop that reads in words runs one time per word (not one time per line of text). A word is separated from other words by whitespace.

Definitions and assumptions     

Suggestions     To count the number of syllables in each word, you should write the method

           public static int countSyllables(String w)
       
This method should run through the characters of the input argument word. Reiterating the rules above, each sequence of one or more vowels in the word should count as a syllable, with one exception: if the lone vowel e or E is at the end of the word, it should not count as a syllable. If any other vowel or more than 1 vowel stand at the end of the word, it should count as a syllable. Y and y will always count as vowels for this problem.

Your method should return the number of syllables in the input word with one exception: it is possible by the above counting system that a word will end up with zero syllables, and your code should make sure that the countSyllables method returns at least one syllable for every word.

You might also find it useful to write a method
           public static boolean isVowel(char c)
       
that returned true if c was one of the possible vowels ('a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y'). Yes, we will count y as a vowel for this problem. This method returns false if c is anything else -- in that case, you can assume c is a consonant. Thus, in order to check if a char c is a consonant, use

       if ( isVowel(c) == false )
       
or

       if ( !isVowel(c) )
       

Sample Runs

Here are two sample runs. You should text your program against these inputs to be sure that everything is working correctly. Remember -- this text is already in the file testfile.txt which is in the Hw6Pr3 folder. You can open this from JCreator. In fact you can paste any text, e.g., your last Hum paper into this file to try it out... be sure you end with END! Here's the example:

Please type in a number of words or sentences, and I will
assess their readability...


Fourscore and seven years ago our fathers brought forth on this continent a new nation conceived in Liberty and dedicated to the proposition that all men are created equal. END Total words: 29 Total sentences: 1 Total syllables: 48 Flesch readability score: 37 -------------------------------------------------- Please type in a number of words or sentences, and I will assess their readability...

The cow is of the bovine ilk. One end is moo the other milk! END Total words: 14 Total sentences: 2 Total syllables: 16 Flesch readability score: 103

Be sure to submit your CS5App.java file under homework 6, problem 3.



Extra Credit

There are two (completely optional) extra credit problems this week, each worth a potential 10% of the assignment's points)...

Part 1 Part one of the extra credit is to extend problem 1 (the ASCII animation of the wandering students) according to your own tastes. You might create a graphical 1d or 2d random walk; or, you may want to have more than one "person" wandering; you may have the wanderers "bounce off" each other or annihilate each other -- creativity is welcome! Do not submit this separately -- just submit it as your Hw 6, Pr 1.

Part 2 Part two of the extra credit is to run the Flesch readability program on one (or more) of large texts of your choice (from the web or your own papers) and then include the resulting scores in a comment at the top of the file. You should also point out somewhere in your paper that the syllable, sentence, or word-counting used by the program was wrong for your chosen text and suggest how you might fix the code so that it would count correctly. Do not change your code from the way it is described in the problem, however, because then it may report different results on our test cases!