CSE 131 Module 5: Methods

Extensions

Extension 1: Methodize It (3 points):

Authors

Refactoring

To earn the points for this extension, go back to a lab or extension you have previously completed, and refactor it using methods to eliminate code duplication.

To demo:

When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.1
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 1


Extension 2: Chase, The Mouse (5 points):

Authors

A Story

Chase, the Mouse, was standing still on the Standard Draw template one day, thinking about the meaning of life. All of a sudden, out of nowhere, a ball began to follow Chase. No matter where Chase went the ball would follow and pester Chase until he moved again. You will be writing the code for the ball.

Procedure

Create a FollowTheMouse class in the mousefollower package. You will have to write a few specific methods for this extension. You can test those with the JUnit test provided in the package. Once all of these methods are written, you will put them to use in the main method to create a Standard Draw template in which a ball follows your mouse. The methods that you must write are:
double[] getMousePosition()
This method returns an array of two doubles, the x and y coordinates of the mouse. You can find the coordinates of the mouse on the standard canvas using StdDraw.mouseX() and StdDraw.mouseY()
  1. Write that method so that the first double in the array that you return is the x coordinate of the mouse, and the second double is the y coordinate of the mouse.
    This method should be very simple.
  2. Test this method using the JUnit test GetMousePositionTest in the mousefollower class. When you run this test, a ball will appear on a Standard Draw template. Try to follow the ball with your mouse while the test runs.
drawBall(double[] position, double radius)
This Method draws the ball wherever it should be in a specific frame.
  1. This should take in an array of 2 doubles that specifies the x and y coordinates of the ball and a double for the radius.
  2. Test this by manually drawing a ball in your main method at a specific x and y coordinate. You can use the following code:
    double[] tester = new double[]{.5, .5}; drawBall(tester, .2); StdDraw.show(2000);
    If this draws a large ball in the middle of your template, then your drawBall() method works!
double[] changePosition(double[] position, double[] mousePosition, double speed)
This should return an array of 2 doubles that represents the new position of the ball
  1. This method takes in an array of 2 doubles that specifies the original position of the ball, an array of 2 doubles that specifies the mouse position, and a double for the speed.
    You are not simply drawing a ball at the position of the mouse. The ball should move at a constant speed towards the mouse at all times. This will require some basic geometry. However, you will not need to use any trigonometric functions. dx and dy are the distances from the ball to the mouse. The legs of the green triangle represent the x and y components of the distance the ball moves in each frame. The hypotenuse of the green triangle represents the total distance the ball moves in each frame. This is, effectively, the "speed" of the ball, distance per frame.
Finally, make sure to implement all of these methods in the main method inside of a while loop, along with the other necessary StdDraw code. It would be helpful to set the initial position of the ball outside of the while loop, and then alter it inside.

To Demo:

You must be able to pass the unit tests, and you should have a ball follow your mouse
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.2
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 2


Extension 3: Build Your Own Calculator! (5 points):

Authors

A How-To Guide

In this extension you shall complete the functionality of a calculator. You accomplish this by creating a series of methods that use the arithmetic, String, boolean, and casting operations.

Procedure

You will be writing two kinds of methods. The first kind will be the operational methods, which take in two parameters, and return the result of some operation. For example:
// Returns the result of adding d1 and d2.
public static double addDoubles(double d1, double d2) {
	return d1 + d2;
}
The second kind of method will be to methods, which take in some value, and cast it to the necessary type. For example:
// takes in an int and returns a double
public static double intToDouble(int in) {
	return (double)in;
}
If the input makes no sense, throw an exception. For example, if someone inputs a String, converting it to an int would make no sense.
So for the method
 public static int stringToInt(String in) {
	throw new UnsupportedOperationException();
}  

you would throw an exception that indicates that this operation is unsupported. When you throw this exception, our code catches the exception, and sends out an error message through the GUI. You will learn more about this in future classes.

Methods

First you will write: Then you will write: Each of these methods should be quite short.

To Demo

You must pass all of the unit tests, and your calculator should work properly
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.3
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 3


Extension 4: Watermelon Puzzle (8 points):

Authors
Adapted from Sit and Solve Brainteasers by Derick Niederman

Warm Up

Five watermelons, each of different weight, have been weighed in pairs to obtain the following weights:

20, 22, 23, 24, 25, 26, 27, 28, 30, 31

One way to solve this would be to figure out a mathematical algorithm for this number of watermelons and work out the weight of each watermelon. Another would be to try all of the possible combinations of weights five watermelons until you found one that has this same set of combinations of weights. Either way you did it, the specific set of watermelons that produces these weights is

[ 9, 11, 13, 14, 17 ]

Procedure

Since we have computers, and know how to write code, trying all of the possible weights of the five watermelons is now much easier. In this extension, you will take in an array of 10 weights, and you will try, iteratively, to come up with the individual weights of the five watermelons.
  1. Find the code for this extension in the watermelons package.
  2. Create two methods in the Watermelons class. There is one finished method that will help you write the other two methods. The two methods you must create are:
    int[] allPairSums(int[] nums)
    This method must be completed first. Given the input array nums, this method computes the pairwise-sum of each distinct pair of index values for that array. For example, given the input {40, 20, 10, 30}, the method must compute the sums of indices (0,1), (0,2), (0,3), (1,2), (1,3), (2,3), returning the array
    {60, 50, 70, 30, 50, 40}
    The ordering of the elements in the returned array does not matter.
    int[] getSolution(int[] originalSums)
    This method returns a solution to the puzzle for the array of 10 integers that are passed into it. The ordering of elements in the array you produce does not matter, as far as the provided unit test is concerned.
    The included method, boolean sameIntArrays(int[] one, int[] two) will help you with this method. When you pass two integer arrays into sameIntArrays, it checks whether the two integer arrays contain the same elements. The order of the elements in the arrays does not matter.
  3. Make sure you pass the provided unit tests. Once it does, you will have a solution to the puzzle.
    For extra fun, go into the code for the Unit test, and inside the int[] genSolution() method, uncomment List ans = genIntsSlow(); and comment out List ans = genIntsFast();. This will pass larger weights into your int[] getSolution(int[] originalSums) method, and so the computation will take longer. It could take up to a minute. This is not required, but it is a neat example of a very large computation.
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.4
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 4


Extension 5: Tic-Tac-Toe (5 points):

Authors

Introduction

The design of software can often be specified using its API, or Application Programming Interface. The API specifies the methods that are offered by the software. Documentation for those methods typically includes: The above should be sufficient to use the software, but it can also form the design document for implementing the software.

Procedure

It is suggested that you implement the methods in the following order:

  1. String[][] genBoard() (actually shown in the video)
  2. void verifyValidRow(int)
    For this assignment, when an improper input is found by methods like this, you are required to throw an IllegalArgumentException.

    An example of that is done for you in verifyValidPlayer, so take a look at that for guidance.

  3. void verifyValidCol(int)
  4. boolean makeMove(String, String[][], int, int)
  5. boolean boardFull(String[][])
  6. boolean winFor(String, String[][])
Other methods are in the class and documentation, but they are already implemented for you:

Play the game

When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.5
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 5


Extension 6: Jackpot (6 points):

Authors

Description

In this assignment you create a slot machine. In this game, you pull (or click on) a lever which causes the reels to spin and land on random shapes. Based on the combination of the shapes and their colors, the player wins a certain amount of money. You will create this game using Sedgewick's StdDraw.

Procedure

Be creative! Many implementations will satisfy the requirements.
Your slot machine must include:
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.6
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 6


Extension 8: Memory Matching (5 points):

Authors

Overview

Your goal in this extension is to create a memory matching game using StdDraw and your growing computer science knowledge. If you've never played a memory matching game before, you can find a truck themed one here to get the general idea. Additionally, you can find a video demoing a solution here.

In this extension, you are going to create a matching game that uses colors rather than images. It should do the following:

Procedure

Be aware that the (0,0) coordinate on the StdDraw canvas is in the lower-left corner while we generally depict the [0][0] index of a two dimensional array in the upper-left, as shown in the drawing below in blue and black respectively. If you store information in arrays, you want to have consistency between the way that information is stored and viewed, e.g. (0,0) should correspond to the same area as [0][0]. You can do this however you like, but it's recommended that you change the scale of the StdDraw canvas so that its coordinates match those of the array. This can be accomplished with the method, StdDraw.setYscale(double bottomValue, double topValue).

Below are the methods you must complete. The first method must pass the unit test. You are welcome to write additional methods to help accomplish this assignment.

Color[][] genBoard()
Generates a new board with 8 different color pairs and returns the 4x4 Color matrix with randomized locations. Must pass the unit test for credit.
void drawBoard(Color[][] board)
Rescales the canvas as described above and draws the hidden or flipped tiles that are in play.
boolean isOver(Color[][] board)
Checks to see if all the matches have been found.
double[] click()
Waits for a mouse to click and release and then returns an array with the click's x and y coordinates.
void playGame()
Plays the game until it is over and then waits for a click to start a new one, at which point it generates a new board.

In this extension, you are going to need while loops that will run indefinitely, waiting for some input from the player. You must use the StdDraw.pause(int msec) method to give your computer a break. If you don't, the computer will waste resources doing absolutely nothing. Below is some sample code to demonstrate what this looks like:

while(!StdDraw.mousePressed()) {  // waiting on a click
	StdDraw.pause(80);
}
// Do something...	
Don't forget that in order to actually run your game you will need a main method.
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.8
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 8


Extension 9: Net Present Value (3 points):

Authors

Present Value

In this assignment, we consider and reason about the time value of money. This is based on the observations:

The suggestion is therefore to reason about all currency in today's dollars. This is called present value.
The ideas discussed here are widely used in economics, finanace, and accounting.

Two Friends and your $1

Suppose you have $1 and two friends who offer to take your dollar under the following circumstances:

Friend One

This friend takes your $1 and gives you back $5 tomorrow.

Friend Two

This friend takes your $1 and gives you back $10 in fifty years.

Which friend is offering you the better deal?

How do we reason about the value of $10 in fifty years? We must first model how the value of money changes over time. We do this by choosing:

We then use the time value of money to compute the following:

Returning to your two friends, let's relate both friends' offers in terms of present value, and compute your profit or loss (your net result).

Net Present Value

Recall we assume a discount rate of 10% (r=0.10) and we regard time annually.
Friend One
  • This friend takes your $1 and gives you back $5 tomorrow.
  • With money changing value annually, $5 tomorrow is the same as $5 today.
  • Computing
    presentValue($5, 0, 0.10) = $5 / (1.0 + 0.10)0
    yields $5.
  • This friend's offer is therefore worth $5 today.
  • Your net gain is the $5 you receive minus the $1 you gave away, so you net $4.
Because your net present value from this deal is positive ($5), you would choose to take advantage of this friend's offer.
Friend Two
  • This friend takes your $1 and gives you back $10 in a fifty years.
  • $10 in fifty years sounds better than $5 tomorrow, but …
  • Computing
    presentValue($10, 50, 0.10) = $10 / (1.0 + 0.10)50
    tell us that this friend's offer is worth about 8 cents today.
  • Your net gain is the 0.08 dollars you receive minus the $1 you gave away, so you net −0.92 dollars.
Because your net present value is negative (−0.92), you would decline this friend's offer.

Product Development Story

Consider the following example from Wikipedia, based on investing $100,000 to create a new product:

In summary, you give away $100,000 and you get $120,000 back. Is this a good deal? Let's look at the returns in terms of Net Present Value (NPV):

Year Present Value
Computation
(for year 0)
Computation
Result
Net Present Value Comments
0
−$100,000

(1+0.10)0
 = −$100,000.00 −$100,000.00 Initial investment, no return until year 1
1
$10,000

(1+0.10)1
 = $9,090.91 −90,909.09 The Computation Result column shows the yearly return of $10,000, discounted by the rate (0.10) so it can be expressed in present (year-0) dollars
2
$10,000

(1+0.10)2
 = $8,264.46 −82,644.63 The Net Present Value column shows the cumulative gain or loss
3
$10,000

(1+0.10)3
 = $7,513.15 −75,131.48
4
$10,000

(1+0.10)4
 = $6,830.13 −68,301.35
5
$10,000

(1+0.10)5
 = $6,209.21 −62,092.14
6
$10,000

(1+0.10)6
 = $5,644.74 −56,447.40
7
$10,000

(1+0.10)7
 = $5,131.58 −51,315.82
8
$10,000

(1+0.10)8
 = $4,665.07 −46,650.75 In present value, the $10,000 received in this year is worth less than half!
9
$10,000

(1+0.10)9
 = $4,240.98 −42,409.77
10
$10,000

(1+0.10)10
 = $3,855.43 −38,554.34
11
$10,000

(1+0.10)11
 = $3.504.94 −35,049.40
12
$10,000

(1+0.10)12
 = $3,186.31 −31,863.09 At the end of 12 years, we have $120,000 but that is worth only $68,136.91 in present (year-0) dollars, with each year's $10,000 discounted to show present value.

The NPV of the $100,000 investment is −31,863.09, which is a substantial loss. Because the NPV is negative, this is not an investment you should make.

Procedure

To Demo

Show your unit test output to a TA.
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.9
Last name WUSTL Key Propagate?
(NOT your numeric ID) Do not propagate
lower case only
e.g. Smith j.smith
1    

Acknowledgements and assertion of integrity

You must select one of the options below
The work submitted here was performed in accordance with this course's policy on collaboration.
On your honor, you have neither given nor received any unauthorized aid on this assignment.

However, the following TAs, students, or professors were supportive in completing this assignment.
Their help was also in accordance with course policies.

Thanks to (leave blank if appropriate):

In spite of seeking help as allowable by this course's policy on collaboration, you were unable to complete this assignment. No credit will be received for this assignment.

You would like to be contacted by an instructor to facilitate staying on track in this course.

Comments about this:

You have NOT abided by this course's policy on collaboration. No credit will be received for this assignment, but by checking this box, no academic integrity violation will be filed for this assignment.

You would like to be contacted by an intructor to faciliate staying on track in this course.

Comments about this:


TA: Password:

End of extension 9