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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 5


Extension 6: Jackpot (7 points):

Authors
Issues: Not ready, need to dictate methods, need more detail.

Description

In this extension you complete the first step towards creating slots, the classic casino game. In this game, you pull a lever and the slots rotate, slow down, and eventually land on some combination. Based on the combination you have the chance to win a certain amount of money. You will create this machine using StdDraw.

Procedure

You are only taking a step towards completing slots, so read the instructions carefully so that you do not do more than you need to.
This step in your implementation of the slots machine must include: A couple of methods that might be helpful in your implementation are: You can add more or fewer methods, depending on how you want your implementation to work, but having these will save you a lot of code writing.
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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 6


Extension 7: Jackpot: Actual Game (7 points):

Authors

Description

In this extension you complete the second step towards creating slots, the classic casino game. In this game, you pull a lever, and the slots rotate, slow down, and eventually land on some combination. Based on the combination you have the chance to win a certain amount of money. You will create this machine using StdDraw.

Procedure

This step in your implementation of the slots machine must include: A couple of methods that you might add when you modify your Jackpot machine: You can have more or fewer methods, depending on how you want your implementation to work, but having these will save you a lot of code writing.
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.7
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 7


Extension 8: Memory Matching (5 points):

Authors
Issues: Not ready yet

Procedure

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 Thomas the Tank Engine themed one here to get the general idea.

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

Be aware that the (0,0) coordinate on the StdDraw canvas is in the lower-left corner while the [0][0] index of a double array is in the upper-left. If you store information is arrays, you want to have consistency between the way that information is stored and viewed. 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 double array.

In order to make this task easier for yourself, you should break the game up into parts and use several methods. Maybe you start out by creating a method to randomly generate the board of colors, then a method to draw the board, then then move on to the game itself.

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(true) {
	if(StdDraw.mousePressed()) {
		// Do something...
	}
	StdDraw.pause(80);
}
Don't forget that in order to actually run you 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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

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?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 9


Extension 10: Color Pairing Module 1 (8 points):

Authors
Motivation: Professor Cytron has trouble dressing himself. He often needs his wife to help guide him when it comes to matching his shirts and pants. Professor Cytron decided it might be worth his time to develop an application that takes into account his wife's color preferences in order to determine whether his outfits match before he goes out.

This module is the first of three in which you will work on developing an application that utilizes basic Machine Learning to determine whether two colors go well together based on past user preferences. For now, we will just worry about implementing the interface along with some basic functionality.

Our initial interface will consist of the following components:

We will make use of the StdDraw HSV color model for this module

  1. Begin by implementing the generatePickers() method in ColorMatcher.java. This method will generate the two hue pickers we will use to construct our HSV model colors.
  2. Continue by implementing the generateSliders() method.
  3. Implement the sampleColor() method
  4. At this point, we will move to the main method and begin to add some functionality to our interface.

Things to consider:

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

This demo box is for extension 5.10
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 10


Extension 11: Color Pairing Module 2 (8 points):

Authors

In this module you will build off of the interface and functionality you developed in the previous color pairing module. Particularly, you will make some small modifications to the interface and back-end functionality, allowing for users to determine how well colors match and for their preferences to be written to a .csv file.

Atfer this module, our interface will include the following modifications:

  1. Begin by replacing the circular sample displays with a t-shirt and pants and updating relevant code to fill these new displays when a color is sampled
  2. Continue by implementing the generateButtons() method.
  3. Implement functionality to test ability to open .csv file
  4. Continue by implementing the writeToCSV() method.
  5. The method should then attempt to write this row to the .csv file

Things to consider:

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

This demo box is for extension 5.11
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 11


Extension 12: Learning From Data (0 points):

Authors

Background

In this assignment, you will program a machine learning algorithm called K-nearest neighbors. You will read data from a file and store that data for your algorithm. You will then use this algorithm to learn information about incomplete data.

Procedure

  1. Download the iris CSV file from your Data_Module5 folder (credit to Machine Learning Respository). This file contains the data that you will be learning from; it is called the "training data" as you will be using this data to train your algorithm and prepare it for learning. The data is about 3 different types of iris plants, where the first column of the data is the sepal length, the second is the sepal width, and the third is the type of iris plant, which is called the "classification." From this data, you will learn what values of sepal length and sepal width belong to a specific iris plant.
  2. Next, you must read the data from the file and store it into a arrays. This can be done using the Scanner and File classes provided by Java. A CSV file, or a Comma-Separated Values file, can have data read from it by using the "," character as a delimiter. We can then get each data value in the file by using "scanner.next()" which reads the next available String in the file. You will want to store the first two columns, sepal length and sepal width, into one array of type double, and the third column, the plant classification, into a second array of type String.
    try {
    	Scanner scanner = new Scanner(new File("your/path/to/iris.csv"));
    	scanner.useDelimiter(",");
    	trainingData = new double[135][2];
    	classification = new String[135][1];
    
    	int dataCount = 0;
    	while (scanner.hasNext()) {
    		trainingData[dataCount][0]   = Double.parseDouble(scanner.next());
    		trainingData[dataCount][1]   = Double.parseDouble(scanner.next());
    		classification[dataCount][0] = scanner.next();
    		dataCount++;
    	}
    	scanner.close();
    	} catch (FileNotFoundException e) {
    		e.printStackTrace();
    	}
    
  3. Now that you have stored the data into arrays, you are ready to learn.
    The data that you have been given is 2-dimensional data, classification data. This means that the data is based on two independent variables, sepal length and sepal width, and a third dependent variable, iris plant type. When plotting the data on a graph, you get something similar to this:

    Iris data plot (credit to mirlab.org)

    From this plot, there are clearly three groupings of points based on the independent variables. The K-nearest neighbors algorithm works as follows:
    Given a new data point, find the K closest points (based on distance) to this new point. It is important for this algorithm that distance be defined in some manner so that the closest points can be determined. For this data, distance is clearly defined by using sepal length and sepal width. For each of those K closest points, get the classification of each point and take the majority, unweighted vote of the classification types. This will result in the new data point being classified the same as its closest points, and so for a dataset with distinct groups of data (such as this dataset), the new data point will usually be correctly classified.

    For example, given a data point with sepal length 5, sepal width 4, and an unknown classification, find the 3 nearest neighbors. Two of the three nearest neighbors are classified as a Setosa, with the third nearest neighbor classified as a Verisicolor. Therefore, the new data point is classified as a Setosa.
  4. The pseudocode for the algorithm is as follows:
    Create a new data sample
    For each data point in the training data
        Calculate the distance from the new data point to the other data point
        If this distance is one of the K smallest distances, store both the distance and the classification of the data point
    After iterating through each row, get the classification of each of the K nearest neighbors
    Take the majority vote amongst those classifications and assign that classification to your new data point
    
  5. Finally, accept sepal length and sepal width as input values. Pass these values into your algorithm to determine the classification of this point. Below are some real data points you can use to test your algorithm. Experiment with K and see how your results may differ!
    SepalLength   SepalWidth   Classification
    5.1	          3.5          Iris-setosa
    4.9	          3.0          Iris-setosa
    4.7	          3.2          Iris-setosa
    4.6	          3.1          Iris-setosa
    5.0	          3.6          Iris-setosa
    7.0	          3.2          Iris-versicolor
    6.4	          3.2          Iris-versicolor
    6.9	          3.1          Iris-versicolor
    5.5	          2.3          Iris-versicolor
    6.5	          2.8          Iris-versicolor
    6.3	          3.3          Iris-virginica
    5.8	          2.7          Iris-virginica
    7.1	          3.0          Iris-virginica
    6.3	          2.9          Iris-virginica
    6.5	          3.0          Iris-virginica
    
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.12
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 12


Extension 13: Learning Which Colors Look Good Together (0 points):

Authors

Background

This assignment is a continuation of "Color Pairing Module 1" and "Color Pairing Module 2". It is highly recommended that you complete the "Learning From Data" assignment before attempting this one. In "Color Pairing Module 2" you wrote to a CSV file, indicating whether or not you thought two colors looked good together. In this assignment, you will use the K-nearest neighbors algorithm to learn which colors look good together based off the data that you collected.

Procedure

  1. The data that you collected in the previous assignment contains two pairs of HSV values for color. This means that the data is 6-dimensional: there are 6 independent variables which result in a classification of that data, you either like the color pairing or you do not. K-nearest neighbors needs distance to be defined, which is not the case for HSV values, so you must convert the values to another representation of color, CIELUV, as you read the values from your CSV file and store them into two arrays, one for training data and another for classification. The reasoning behind this is explained below (credit to Roman Garnett).
    Differences in human perception of color are nonlinear due to the way that the eyes work, so taking Euclidean distance in typical color spaces like RGB or HSV can be misleading. In such color spaces, two pairs of colors could be separated by the same "distance" but be perceived to be different to different degrees. The CIE* color spaces try to map colors to a space where Euclidean distance corresponds to human perceptual differences, by carefully modeling human perception and human eyes.
    To convert HSV to CIELUV, you can use the following code by passing in the hue, saturation, and value of a color. The output is a double array containing the L, U, and V values.
    public static double[] getCIELUV(double hue, double sat, double val) {
    	//HSV --> RGB
    	double R = 0;
    	double G = 0;
    	double B = 0;
    	if (sat == 0) {
    		R = val * 255;
    		G = val * 255;
    		B = val * 255;
    	} else {
    		double tempH = hue * 6;
    		if (tempH == 6) tempH = 0;
    		int i = (int)tempH;
    		double tempOne = val * (1 - sat);
    		double tempTwo = val * (1 - sat * (tempH - i));
    		double tempThree = val * (1 - sat * (1 - (tempH - i)));
    		switch (i) {
    			case 0: R = val; G = tempThree; B = tempOne; break;
    			case 1: R = tempTwo; G = val; B = tempOne; break;
    			case 2: R = tempOne; G = val; B = tempThree; break;
    			case 3: R = tempOne; G = tempTwo; B = val; break;
    			case 4: R = tempThree; G = tempOne; B = val; break;
    			case 5: R = val; G = tempOne; B = tempTwo; break;
    		}
    		R *= 255; G *= 255; B *= 255;
    	}
    	
    	//RGB --> XYZ
    	R /= 255; G /= 255; B /= 255;
    	if (R > 0.04045) { R = Math.pow((R + 0.055 / 1.055), 2.4); } 
    	else { R /= 12.92; }
    	if (G > 0.04045) { G = Math.pow((G + 0.055 / 1.055), 2.4); } 
    	else { G /= 12.92; }
    	if (B > 0.04045) { B = Math.pow((B + 0.055 / 1.055), 2.4); } 
    	else { B /= 12.92; }
    	R *= 100; G *= 100; B *= 100;
    	double X = R * 0.4124 + G * 0.3576 + B * 0.1805;
    	double Y = R * 0.2126 + G * 0.7152 + B * 0.0722;
    	double Z = R * 0.0193 + G * 0.1192 + B * 0.9505;
    	
    	//XYZ --> CIELUV
    	double U = (X * 4) / (X + (Y * 15) + (Z * 3));
    	double V = (Y * 9) / (X + (Y * 15) + (Z * 3));
    	Y /= 100;
    	if (Y > 0.008856) { Y = Math.pow(Y, 1.0/3.0); } 
    	else { Y = (Y * 7.787) + (16.0 / 116.0); }
    	double xVal = 95.047;
    	double yVal = 100.000;
    	double zVal = 108.883;
    	double uVal = (xVal * 4) / (xVal + (yVal * 15) + (zVal * 3));
    	double vVal = (yVal * 9) / (xVal + (yVal * 15) + (zVal * 3));
    	
    	double cieL = (116 * Y) - 16;
    	double cieU = 13 * cieL * (U - uVal);
    	double cieV = 13 * cieL * (V - vVal);
    	
    	double[] cieluv = {cieL, cieU, cieV};
    	return cieluv;
    }
    
  2. Now that you have stored the data into arrays, you are ready to learn. The K-nearest neighbors algorithm is the same as for the 2-dimensional data in the "Learning From Data" assignment, with the only difference being that the data now is 6-dimensional. Instead of using the 2-dimensional formula for distance, use the 6-dimensional formula for distance.
    For example, given a new data point containing the values L_a, U_a, V_a, L_b, U_b, V_b and and a training data point L_c, U_c, V_c, L_d, U_d, V_d, the distance formula would be as follows:
    Math.sqrt(  Math.pow(L_a - L_c, 2) + Math.pow(U_a - U_c, 2) + Math.pow(V_a - V_c, 2) 
    		  + Math.pow(L_b - L_d, 2) + Math.pow(U_b - U_d, 2) + Math.pow(V_b - V_d, 2) );
    
  3. After implementing the K-nearest neighbors algorithm, sample a new pair of colors from your color picker and store those values (converted to CIELUV). Pass the values into your algorithm with different values of K and see how the algorithm classifies your data.
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.13
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 13


Extension 400: Watermelon Puzzle (C++) (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.

In this extension we will introduce vectors which are defined in the vector header. Vectors work a lot like arrays with a couple very important differences. Before you start this extension, familiarize yourself with the vector class

  1. Find the code for this extension in the watermelons package.
  2. Take a look at watermelons.h and familiarize yourself with the functions required.
  3. Create two methods in the Watermelons source file. 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, bool sameIntArrays(vector one, vector two) will help you with this method. When you pass two integer arrays into sameIntArrays, it checks whether the two integer vectors contain the same elements. The order of the elements in the arrays does not matter.
  4. Make sure you pass the provided tests in WatermelonsTest. Once it does, you will have a solution to the puzzle.
When you done with this extension, you must be cleared by the TA to receive credit.

This demo box is for extension 5.400
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 400


Extension 500: Lab Methods (C++) (5 points):

Authors

Introduction


Methods

We strongly suggest that you proceed one method at a time through the work below, testing each time to be sure what you have written so far is correct.

If you show up for help with a bunch of methods that don't work because you typed them all in before testing anything, we may not be able to help you until you clean up your code and focus on one method at a time.

  1. Write and test the method sumDownBy2 with the following specification.
    PARAMETERS:   an integer n
    RETURN VALUE: the sum of the positive integers n + (n-2) + (n-4) + ...
    EXAMPLES:     sumDownBy2(7) is 7+5+3+1 = 16
                  sumDownBy2(8) is 8+6+4+2 = 20
                  sumDownBy2(0) is 0
                  sumDownBy2(-1) is 0
    
    sumDownBy2 works properly.

    Continue the lab in this fashion: write code, test the code, and then move forward.


  2. Write and test a method harmonicSum with the following specification.
    PARAMETERS:   a positive integer, n
    RETURN VALUE: the sum 1 + 1/2 + 1/3 + ... + 1/(n-1) + 1/n
    
    Warning: Think carefully about this method's return type!


  3. Write and test a method called geometricSum with the following specification.
    PARAMETERS:   a non-negative integer, k
    RETURN VALUE: the sum 1 + 1/2 + 1/4 + 1/8 + ... + 1/Math.pow(2,k)
    


  4. Write and test a method multPos that takes in two positive integers and returns their product.
    PARAMETERS:   positive integers j and k
    RETURN VALUE: the product j*k
    
    You must accomplish this without using the multiplication operator. Use iteration and repeated addition to form the product.

  5. Write and test a method mult that takes in two integers and returns their product. Each integer could be positive, negative, or zero.
    PARAMETERS:   integers j and k
    RETURN VALUE: the product j*k
    
    Do this by calling your multPos method:
    • Pass multPos the absolute values of j and k. It should return the product of those positive values.
    • Compute this method's return value based on the result of multPos and based on the signs of j and k.

  6. Write and test a method expt with the following specification. Use repeated multiplication. (Do not use the built-in exponentiation method.)
    PARAMETERS:   integers n and k, where k >= 0
    RETURN VALUE: the value of n to the power k
    EXAMPLES:     expt(3,2) is 9
                  expt(5,0) is 1
                  expt(2,5) is 32
    

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

This demo box is for extension 5.500
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 500


Extension 600: Studio Methods (C++) (5 points):

Authors
If necessary, review studio procedures before starting.

Warmup


Overview

In this studio you will explore the following two concepts: If necessary, review the slides and text material in chapter 2.1 concerning methods. Once your group is ready, move on to the next section where you will write and test some methods.
Important! Today you must rotate who is doing the typing as you move from one method to the next. Every person in your group must have a chance to be the lead person at the keyboard, for at least one method described below.

All group members are encouraged to help the lead person at the keyboard.

In preparation for the exercises below, open in eclipse the following, found in the studios source folder of your repository:

Methods

In the work you see below, you should be asking yourselves the following as you write code:
sum
Define a method that accepts two integers and returns their sum as an integer.
This has already been completed for you to serve as an example.
  • To run the JUnit test, go to the Package window, right- (control-) click on MethodsTest, drag down to Run as, and select JUnit Test.
  • The tests will now run and this should not take much time.
  • When the tests have completed, look at the the JUnit window, which should now be open on the left of your screen.
  • You should now see a a reddish stripe, indicating that at least one test failed.
    The tests that failed did so because you have not yet written the methods for those tests. So don't worry (yet).
  • You should see just in front of the testSum entry a happy green check mark, because that test did pass.
  • Take a look at MethodsTest and the testSum method therein. See how it uses
       assertEquals(7, Methods.sum(3,4));
    
    to test the sum method?
  • Add another line in testSum that ensures the sum method works on negative values as well.
mpy
This one is also done for you, but a mistake has been made on purpose, so you can see what happens when JUnit finds that your code does not pass a test.
avg3
sumArray
Write a method sumArray that takes in an array of doubles and returns their sum as a double.
average
Write a method average that takes in an array of doubles and returns their average as a double.
Hint Call the method you already wrote to compute the sum instead of rewriting or copying code.

Your call
As a team, think of a simple method. The method must return some kind of value so it can be tested.

Give your method a name and a specification (input types and return type), and implement it in the Methods class.

In the MethodsTest class, insert testing code like what you see for the other methods.

You must precede the test method by a @Test directive. Get help if necessary.

Pig Latin
OK here's a fun one. Write a method named pig that takes ina String and returns a String. That method should return the pig latin transformation of its input.
Some helpful information:
  • If s is a String, then s.substring(0,1) returns the first character of s.
  • If s is a String, then s.substring(1) returns all but the first character of s.
  • For more information, see substring.

Before you write the code, look at the test! All you have to do to satisfy the test is to return a string that begins with the input's second character, appends the input's first character, and then appends "ay" at the end.

This is not really pig latin, but it does satisfy the test I gave you.

If you want to go for the real thing, read the article and recode so that your code does a true pig latin transformation. Add some more tests to show off your improvement. For example: scramamscray.

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

This demo box is for extension 5.600
Last name WUSTL Key Propagate?
(or your numeric ID) Do not propagate
e.g. Smith j.smith
1 Copy from 1 to all others
2 Copy from 2 to all others

TA: Password:

End of extension 600