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.
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:
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.
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
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:
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.
public static void printMenu()
public static char advanceChar(char c, int n)
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
charAt(int i) is a method available to Strings
that returns the String's ith character. For example,
String s = "hello";
H.out.print(s.charAt(0)); // prints the char 'h'
H.out.print(s.charAt(1)); // prints the char 'e'
H.out.print(s.charAt(2)); // prints the char 'l'
H.out.print(s.charAt(3)); // prints the char 'l'
H.out.print(s.charAt(4)); // prints the char 'o'
length() is a method available to Strings that
returns the String's length. For example,
String s = "hello";
H.pl(s.length()); // prints out the integer 5
Notice that the length is one more than the index of the last character in the
String when using charAt. char values and int
values. However, if you want the result to be a char, you will have
to cast it, e.g.,
char result;
result = c + 1; // error! cast needed
result = (char) (c+1); // OK
Submission Be sure to submit your CS5App.java file under
homework 5, problem 2.
The Menu Your program should offer the user the following menu of
options:
The purpose of this assignment is to do the computations using only primitive
arithmetic. Do not call any functions from the
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
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!
power with
this signature:
public static double power(double b, int p)
Here is an example comment for this method (the same idea may be applied to any
method):
This function should work for any nonnegative integer value for
//
// Method name: power
//
// Inputs: the base "b" (a double), the power "p" (an int)
// Output: b to the p power (a double)
//
public static double power(double b, int p)
{
// code goes here...
}
p.
You should assume that any number (including 0.0) raised to the power 0
is defined to be 1.0. Hint: use the factorial example
that was covered as an example in class as a guide!
factorial with
this signature:
public static double factorial(int n)
Although the factorial will always be an integer, it can quickly exceed the size
of either of the integer types. Therefore, it should be computed, stored, and
returned as a double. Use the factorial function from class as a
guide.
exp which uses this series to approximate the value of
e raised to a given power. To do this, you should sum the series
that appears below and then return that sum. The signature of the method
exp should be
public static double exp(double x, int n)
The method exp should take one double value
(x) and one int value (numTerms) as an
input parameters. Your code will find e to the x power
by summing numTerms terms of the series below. (You can't use your
power method directly to find e to the x
power, because x may not be an int. Also, using
Math.exp is not permitted for this problem for obvious reasons!)
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:
Here,
0 1 2 3 4
x x x x x x
e = --- + --- + --- + --- + --- + ...
0! 1! 2! 3! 4!
x might be positive or negative. For our purposes, we will
make x a value of type double.
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.)
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:
The
0 1 2
x x x
--- + --- + --- +
0! 1! 2!
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.
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!