Homework 05



Assignment: Three problems, worth 15, 20, and 15 points respectively (plus up to 20% extra credit on problem 2). Reading: Your CS5 lecture notes and the online readings for week 5.




Problem 1     What's going on?     [topic: understanding and explaining java methods and code]

For this problem, the code is provided for you and your job is to determine what the code is doing, to explain it in one paragraph, and to describe how to improve it in another paragraph. (There is also an open challenge, as explained at the end.)

Begin by going to the files for download page; download (and extract/unzip) the Hw5Pr1.zip file. Once you have done this, take a look at the code (and feel free to run it...). Here is a copy for reference:


     /*
      * main is where it all begins...
      */
     public static void main(String[] args)
     {
         H.cls();                                      // clearing the screen with blank lines
         H.pl("Welcome to the mystery program.");      // welcome the user
     
         H.pl("Input two words:  ");                   // prompt the user
         String word1 = H.nw();                        // get the first of two words
         String word2 = H.nw();                        // get the second of two words
     
         H.pl("The answer is " + wgap(word1,word2));   // print the "answer"
     }
     
     
     /* This method (wgap) takes two Strings as input and outputs a double.
      * We don't comment further, because that's the "mystery"...
      */
     public static double wgap(String w1, String w2)
     {
         double d = 0.0;
     
         for (int i=0 ; i<4 ; ++i)
         {
             d += cgap(w1.charAt(i), w2.charAt(i));
         }
     
         return d/4;
     }
     
     
     /*
      * This method (cgap) takes two chars as input and outputs an int.
      *   We don't comment further, because that's the "mystery"...
      */    
     public static int cgap(char c1, char c2)
     {
         int d = 0;  
     
         if (c1 > c2)
         {
             // Math.min returns the smaller of its two inputs
             d = Math.min(c1-c2, 26-(c1-c2));  
         }
         else // c2 >= c1
         {
             d = Math.min(c2-c1, 26-(c2-c1));
         } 
         return d;
     }

What to do...

If you'd like an additional challenge, try to find a pair of English words that maximizes the "Answer" that is printed out by this code.

Note that this code uses the charAt method. As you might expect, charAt returns the char at a particular position in a String. For example,


     String s = "hello";
     
     char c = s.charAt(0);  // the variable c now holds the char 'h'
     
     c = s.charAt(4);       // now the variable c holds the char 'o'

This problem will be graded on the clarity and understanding you express in your two paragraphs. You don't need to change the code unless you'd like to.

Submission Submit your CS5App.java file (with the two required paragraphs and any optional changes you might make) under Homework 5, Problem 1.







Problem 2     Code Breaker     [topic: looping, methods, and String manipulation]


Pair Programming Problem As in the last two assignments, Hw5 offers the option of pair-programming with one problem, this "Caesar Cipher" or "Code Breaker" problem. As before, pair programming is optional, though strongly encouraged, except if you are doing this homework in order to "work ahead," in which case you need to do the assignment by yourself. If you do work in pairs, please be sure that each person codes and each person plans ahead/checks for errors half the time. And, whether working in a pair or not, please add a comment on how this problem went at the top of your file.

The Caesar Cipher is a straightforward and not-too-secure encryption scheme. This problem asks you to write a program to help a human break a Caesar-cipher encoded message. In addition, this program asks you to provide a menu of options related to computing with Strings and characters.

In the Caesar Cipher each letter in a plain text message gets shifted by one or more places in the alphabet. In addition, the alphabet is assumed to wrap from 'z' around to 'a' . For example, when the string "hello" is shifted forward by one letter, it becomes "ifmmn"; when shifted forward by 14 letters, it becomes "vszzc" and so on.

The menu Your program should offer the user the following options:

  Welcome to the Code making and code breaking program!
  Options:  (0) shift a line of text ahead by 13 characters (rot13)
            (1) shift a line of text ahead by n characters
            (2) shift a line of text ahead by 1-26 characters
            (3) extra credit:  find the best decoding(s) of a line of text
            (9) quit
Option 0 was considered carefully in class -- it implements the old-fashioned punch-line-hiding strategy of rotating a line of text 13 characters. Option 1 does the same thing, but for n characters, where the user may choose n. Option 2 does the same thing for all values of n from 1 to 26 (and so does not need to ask for n). The idea is that a human would then be able to easily determine which of the 26 is a valid message. Be sure print out all 26 -- including the original text again! The final option is only if you're interested in trying it: it takes in an encoded line of text and outputs the best decoding automatically.

You may assume that all of the characters in the input text will be spaces or lowercase letters. Spaces should not change at all for any of the options.

Required methods Your code must write and use two methods -- yes, it's possible to write it without these methods, but the goal of this week is to provide practice using them! Here are their signatures:

     public static void printMenu()
     public static char advanceChar(char c, int n)
The printMenu method simply prints the menu shown above. It does not have a return value (void) and does not take any inputs. The input should be obtained back in main.

As its signature suggests, there are two input arguments for advanceChar: a char c and an int n. The method should return a char which is n spaces ahead of c in the alphabet. The char should "wrap" from 'z' to 'a', as discussed in class. In addition, it should not change the space character, ' ' at all. As with all methods you write, be sure to include a comment above it documenting its inputs, outputs, and purpose. A couple of points will be alloted to your method comments.

The following is an example run from my program:

  Welcome to the Code making and code breaking program!
  Options:  (0) shift a line of text ahead by 13 characters (rot13)
            (1) shift a line of text ahead by n characters
            (2) shift a line of text ahead by 1-26 characters
            (3) extra credit:  find the best decoding(s) of a line of text
            (9) quit
  Your choice: 0

Please type a line of text:
ifmmp

Shifted ahead 13 characters, your text is
vszzc

  < menu omitted to save space >
  Your choice: 1

Please type a line of text:
ifmmp

Choose an amount to shift (1-26): 25

Shifted ahead 25 characters, your text is
hello

  < menu omitted to save space >
  Your choice: 2

Please type a line of text:
ifmmp uifsf nz obnf jt ebwje

The following are the 26 possible decodings:

jgnnq vjgtg oa pcog ku fcxkf
khoor wkhuh pb qdph lv gdylg
lipps xlivi qc reqi mw hezmh
mjqqt ymjwj rd sfrj nx ifani
nkrru znkxk se tgsk oy jgboj
olssv aolyl tf uhtl pz khcpk
pmttw bpmzm ug vium qa lidql
qnuux cqnan vh wjvn rb mjerm
rovvy drobo wi xkwo sc nkfsn
spwwz espcp xj ylxp td olgto
tqxxa ftqdq yk zmyq ue pmhup
uryyb gurer zl anzr vf qnivq
vszzc hvsfs am boas wg rojwr
wtaad iwtgt bn cpbt xh spkxs
xubbe jxuhu co dqcu yi tqlyt
yvccf kyviv dp erdv zj urmzu
zwddg lzwjw eq fsew ak vsnav
axeeh maxkx fr gtfx bl wtobw
byffi nbyly gs hugy cm xupcx
czggj oczmz ht ivhz dn yvqdy
dahhk pdana iu jwia eo zwrez
ebiil qebob jv kxjb fp axsfa
fcjjm rfcpc kw lykc gq bytgb
gdkkn sgdqd lx mzld hr czuhc
hello there my name is david
ifmmp uifsf nz obnf jt ebwje

  < menu omitted to save space >
  Your choice: 9

czf czf!

Commenting your methods...

Here is an example that has everything the graders will be looking for in your comments for each method: name, inputs, and outputs. Feel free to use this one (or something equivalent)!


     //
     // Method name:    advanceChar
     //
     // Inputs:         a char "c" and an int "n" that indicates the number
     //                 of letters to move forward from "c" in the alphabet.
     //
     // Output:         the char that is n places after c, wrapping as needed
     // 
     public static char advanceChar(char c, int n)
     {
       // code goes here...
     }

Hints

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







Problem 3     the method math menu     [topic: using loops and methods]

In this problem you will write methods using for and while loops that compute some fundamental mathematical functions.

The Menu Your program should offer the user the following menu of options:

  Welcome to week 5's math menu!
  Options:
    (0) Compute a factorial
    (1) Compute a power
    (2) Compute e to the x using n Taylor series terms
    (9) Quit
The purpose of this assignment is to do the computations using only primitive arithmetic. Do not call any functions from the Math package.

Your code is required to create and use at least the three following methods -- yes, it can be done without them, but that this week's theme!

Mathematical Background

The number e is the base of the natural logarithm and is equal to about 2.7. It happens that the value of e raised to any power x can be computed by the series:

 
           0     1     2     3     4
    x     x     x     x     x     x
   e   = --- + --- + --- + --- + --- + ...
          0!    1!    2!    3!    4!

Here, x might be positive or negative. For our purposes, we will make x a value of type double.

***** Start of Important Warning *****

Notice that the variable x is being used in two very different ways in the above series. On the left, x is the power to which e is being raised. On the right, x is NOT the power -- it is the base! Thus, x will be passed into the power method as the first argument (base). (This is one reason why x is a double, not an int.)

***** End of Important Warning *****

Note The initial term in the above series is just the value 1, but it still counts as a term! Thus, if numTerms is 3, you will sum up the following three terms:

 
      0     1     2
     x     x     x
    --- + --- + --- + 
     0!    1!    2!

The exp method needs to add each of these terms to a variable that is holding the running total, and then it should return this total.

Notice that each term uses both a power (in the numerator) and a factorial (in the denominator). You should use your own power and factorial methods to compute these values -- that's why you wrote them for parts 1 and 2 of this problem.

Here is a single run from my program, as a guide to a suitable interface and some test cases. You do not need to round your answers.

  Welcome to week 5's math menu!
  Options:
    (0) Compute a factorial
    (1) Compute a power
    (2) Compute e to the x using n Taylor series terms
    (9) Quit
  Your choice: 0

Input an int: 6

6 factorial is   720.0


  < Menu omitted to save space >
  Your choice: 1

Input a double base and an integer power:
0.1
3

0.1 to the 3 power is   0.001

  < Menu omitted to save space >
  Your choice: 2

Input a double power and I will raise e to that power: 1.0
Enter the number of terms you'd like to use (an int >= 1): 3

The result is 2.5

  < Menu omitted to save space >
  Your choice: 2

Input a double power and I will raise e to that power: 1.0
Enter the number of terms you'd like to use (an int >= 1): 20

The result is 2.7182818284590455

  < Menu omitted to save space >
  Your choice: 2

Input a double power and I will raise e to that power: -10
Enter the number of terms you'd like to use (an int >= 1): 3

The result is 41.0

  < Menu omitted to save space >
  Your choice: 9

Thanks for your e^xceptional company!

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

Extra Credit

For extra credit this week (up to 20%), the task is to improve your Caesar-cipher decoding program by adding the #3 menu option that prints out only the correct message when given an encrypted line of text. If your program prints out a few lines (between 2 and 5), all of which it considers possibly correct, that is OK for the extra credit, as well. Keep in mind that at least the overall goal is to narrow it down from 26 possibilities to one.

Note: this is a challenging problem! You may assume the message is an English sentence at least 30 characters long. You may also assume that all input characters are blanks or lowercase letters, as in problem 2. There are a number of possible approaches which involve looping through each of the 26 possible decodings and examining their contents... . And, as with anything involving human language -- don't expect your program to work every time... good luck!