## CSE 131 Module 2: Choice & Iteration

Important!

Before beginning any work, do a Team...Pull in your repository.

## Extension 1: Image Processor With Iteration (6 points):

Authors

### Manipulating an Image Raster

Directions: In the imagetransforms package, modify the provided Transforms Java program to implement the methods as described below. Your methods will use iteration (either while loops or for loops) to operate on the pixels of a picture.

#### Notes

• To run this extension, right (control) click on Main and choose Run as... then Java Application.

This extension uses the same base code as the filter extension.

• The Picture class is a Sedgewick class whose API is documented on page 720 of our text. The coordinates are expressed using the standard in computer science graphics: the coordinate (x,y) denotes the pixel that is
• x pixels to the right of the leftmost edge of the picture
• y pixels down from the top edge of the picture
Thus, (0,0) is the top left corner of the picture.
• Pixel addressing follows the common Java convention: if there are w horizontal pixels, then 0 is the first (leftmost) and w-1 is the last (rightmost).
• Almost all of the methods are written in terms of two Picture parameters:
• source: the picture to be used as input to your transformation
• target: the picture area to be used as output from your transformation
There is just one exception: the gradient method produces its output without needing a source. Its only parameter is target.

• Each Picture has a width and a height, and these can be obtained for a Picture p as follows:
```  int width  = p.width();
int height = p.height();
```
• To find the Color of a pixel at location x,y, you use
```  Color c = source.get(x,y);
```
• To set the Color of a pixel at location x,y to the color c, you use
```  target.set(x,y,c);
```

#### Instructions

Each of the methods described below is found in the Transforms class.

1. The provided method flipHoriz(Picture source, Picture target) flips the image horizontally.

Look at the code given to you for this example carefully. It is broken into simple steps and the comments help explain why the pixel indexing works.

2. Complete the method flipVert(Picture source, Picture target) that flips the image vertically.
3. Complete the method flipHorizLeftHalf(Picture source, Picture target) that flips the left half of the image horizontally.
The left half of the target image should be same as the source, but the right half of the target image should be the mirror of the left half of the source.

4. Complete the method flipVertBotHalf(Picture source, Picture target) that flips the bottom half of the image vertically.
5. Complete the method gradient(Picture target) that takes a single Picture as a parameter. Your code should create a color gradient by computing the following for each pixel:
• The amount of red in each pixel increases gradually from 0 at the left edge of the image, to 255 at the right edge of the image.
• The amount of green in each pixel increases gradually from 0 at the top edge of the image, to 255 at the bottom edge of the image.
• The amount of blue in every pixel should be 128.
Thus, each pixel will have a different color depending on its position. For example, the pixel at the top left will have red=0, green=0, and blue=128. The pixel about 1/4 of the way down on the right edge will have red=255, green=64, and blue=128.
Develop an expression for the amount of red and green in each pixel, given the x and y position of that pixel and the width and height of the image:
```   int amountRed   = .....
int amountGreen = ....
```
Then set the pixel at (x,y) to a color based on those computations:
```    target.set(x, y, new Color(amountRed, amountGreen, 128));
```

Note There are other methods in the Transform class, but they are the subject of other extensions. Once you have completed the above work, demo and you are done with this extension.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 2.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

TAs double check!
• This demo box is for extension 2.1
• The student has committed and pushed the work, and verified that it appears at bitbucket.

## Extension 2: Loop Invariants (7 points):

Authors
Loop invariants are a tool for proving that a loop computes some useful result. This topic is covered in a discrete math course, but you can try your hand at some loop invariant proofs in this extension.

However, you must agree to the following:

• You will watch this video before you ask any questions.
• You will meet with the instructor as indicated in the steps below.
• Those meetings will take place in office hours during the semester, or during times otherwise arranged with the instructor.
• Like all extensions, you get to choose whether you want to do this extension. However, if you want to do it, then your work on this extension must be complete before the first extension deadline.

#### Warm Up

Loops can be used to execute many simple operations. For instance:
For some a and b:
```		int ans = 0;
int i = 0;

while(i != b){
i = i + 1;
ans = ans + a;
}
```
This code computes the product of a and b.
We have discussed this in this video, and you can find the code in the loopinvariants package of the extensions folder. You are encouraged but not required to create other classes in that package to help you with your work below.

#### Part 1

Consider the following examples:
1. ```		int ans = a;
int i = 0;

while(i != b){
i = i + 1;
ans = ans + 1;
}
```
The above code computes the sum of a and b.
2. ```		int ans = 1;
int i = b;

while (i != 0){
i = i-1;
ans = ans * a;
}
```
The above code computes a to the power of b
3. ```		int ans = 0;
int i =   a;

while (i >= b) {
i   =   i - b;
ans = ans + 1;
}
```
The above code computes a divided by b using integer arithmetic.
1. Find the Loop Invariants of these three loops. Once you have found them, talk to the professor to make sure that they are correct.
2. Sketch a mathematical proof to show that these loops actually return what we say that they return. You will not need to turn this in to the professor, but it will be good practice for Part 2.

#### Part 2

Consider the following code:
```		int power = 0;
int i     = a;

while (i%2 == 0) {
i = i/2;
power = power + 1;
}
```
1. Create a table of values for a, i, and p for a couple of initial values of a. Use this table to find the relationship between a, i and p. Hint: a is a function of i and p.
2. This relationship is the Loop Invariant of this code. Write a mathematical proof that the loop invariant stays constant throughout the iterations. Every step must proceed from what came before it, with no gaps in logic. Any flaw will cause your submission to be rejected, but you can continue revising your proof until the end of the semester when extensions are finally due.
3. What does this relationship say about the natural numbers (your values of a)? The fact that this relationship is true for all numbers is actually a mathematical theorem.
That theorem is used in the Miller–Rabin primality test, which is a fast probabilistic algorithm for testing the primality of an integer:
• If that test says no, then the integer in question is definitely not prime.
• If that test says yes, the the integer in question might be prime.
The uncertainty can be reduced arbitrarily by more testing.

#### To Demo

You must
• Show the loop invariants of all of the above loops
• Have a mathematical proof for the correctness of the outcome of the final loop
• Understand your own proof. You will be asked questions about it when you turn it in
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 2.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

TAs double check!
• This demo box is for extension 2.2
• The student has committed and pushed the work, and verified that it appears at bitbucket.

## Extension 3: One-Rep Max Weight Calculator (3 points):

Authors
Disclaimer:
• The values computed in this assignment are based on published formulas, but you are advised to undertake this and all forms of exercise with the advice and consent of a physician.
• In particular, performing a one-rep max movement unprepared or unsupervised can result in injury.
• You are therefore especially cautioned against that form of training without adequate supervision and coaching.
The authors of this extension and all personnel involved with this course are not licensed medical care providers; they represent that they have no exepertise in diagnosing, examining, or treating medical conditions of any kind, nor in determining the effects of any specific exercise. The data computed by this exercise are for informational and instructional purposes only.

### Overview

In weight training, the volume of work completed in one exercise (often called a set) is typically specified as a given weight that is moved a specified number of times. These are respectively called the weight and reps (abbreviates repetitions) of that set.

In this extension, you will create a one-rep max calculator. This calculator hypothetically calculates a weight that a subject could move for one repetition, given that the same subject can successfully complete r reps (in the range of 2…12) at a lighter weight.

• Beyond 12 reps, the formula we use is not considered accurate.
• The stated value for r is generally considered to be the number of times the weight can be moved before failure: the subject can complete r reps at the stated weight, but no more.

While a person may never attempt that one-rep max movement, the one-rep max weight is canonical, in that it can then be used to compute lighter weights that should be feasible for the subject at a desired number of reps.

Your solution will compute and print:

• The one-rep max weight based on a formula described below.
• The weight that should be feasible for a stated number of reps.
• Percentages of the one-rep max weight from 95% to 50% in decrements of 5%.

### Example

Consider a subject who can successfully bench 225 pounds 10 times before failure.
• What is this subjects current one-rep max bench weight?
• How much weight should that subject be able to bench to get 5 reps before failure?
• What percentage of this subject's max bench is the weight that can be benched 5 times?
Input
• Successful weight: 225 pounds
• Successful reps: 10
• Desired reps: 5
Output
```One-rep max: 300
Weight for 5 reps: 255
95% 1 RM: 285
90% 1 RM: 270
85% 1 RM: 255
80% 1 RM: 240
75% 1 RM: 225
70% 1 RM: 210
65% 1 RM: 195
60% 1 RM: 180
55% 1 RM: 165
50% 1 RM: 150
```

### Procedure

• First take a look at this one-rep max caculator.
• If you try it for some sample values, you will see that it produces results that may not work in an actual gym, because the smallest plate one can find in most gyms is 2.5 pounds.
• Our calculator takes in a third input, which is how many reps the person wants to perform, and calculates a weight to be performed at that number of reps.
• Our one-rep max calculations will be based on the Epley Formula, so study that material sufficiently well to complete this extension.
• Create a OneRepMax class in the onerepmax package of the extensions folder.
• Arrange for that program to prompt the user for the inputs needed for this computation.
• Compute and print the results as shown in the sample ouptut above for the inputs provided in the run of your code.
• You must:
• Check that the inputs provided are reasonable. Print a suitable message and exit if any inputs are unreasonable.
• Use iteration to produce the table of percentages of the one-rep max weight.
• Produce weight values that are rounded to the nearest 5 pounds, so that the least weight needed on a bar is 2.5 pounds on each side.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 2.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

TAs double check!
• This demo box is for extension 2.3
• The student has committed and pushed the work, and verified that it appears at bitbucket.

## Extension 4: Rock-Paper-Scissors (5 points):

Authors

### Rock-paper-scissors

The game of Rock-Paper-Scissors (hereafter, RPS) is a two-player game that can be used to avoid boredom and to settle disputes.

In this extension you will create a simulated player who will randomly throw rock, paper, and scissors with equal likelihood. Your task is to play against this bot and keep score of who wins over a series of games.

#### Procedure

Update your workspace as usual, and find the rockpaperscissors package in the extensions source folder. Create a new class RPS there, and you are ready to begin your development.

It is suggested that you develop code in small steps, so that you can proceed from confidence to confidence, and not have a big pile of untested code to debug at the end.

To help motivate this approach, the TAs will not help you unless you have shown progress based on these steps. Ask for help as soon as you need it, but please follow the steps below so that you can gain confidence.

The steps you might consider are as follows:

1. What inputs does your program need? First, get your program to accept those inputs and print them out so you can see they are set properly.
This means that you should type in the code to prompt the user for the input(s), print out the values of those inputs, and that's all for now. Run your proram at this point and make sure it is behaving as you want.

What inputs do you need? There's no reason to ask for more than is necessary. At a minimum, you have to know how many rounds of RPS to play before printing the resulting statistics.

2. Next, create a loop that simply iterates the desired number of times.
Again, run your program. You may want to print something out in your loop so you can verify that the loop works correctly.
3. You next can make the concept of the random player real. This means declaring a variable name of a suitable type to represent this concept, establishing the variable's initial value.
What is the concept of the player? There are many details about the player that appear unnecessary: the player's name, address, cell phone number.

On the other hand, if we are going to play RPS, we need to know what move the player has made. This is the important concept.

How do we represent the choice of rock, paper, or scissors? This is left up to you, so try for something simple. It may help to recall how Paul Revere was (poetically) told of how the British were coming: one if by land, two if by sea.

In otherwords, an int encoded the manner of invasion.

If there were only two choices, why didn't Paul use a boolean? Sadly, Boole was not yet born.
4. In your loop, you should modify this variable's value to reflect the associated player choosing randomly among rock, paper, and scissors on each iteration.
You've seen how to use the random number generator to pick between two outcomes. Now you must pick between three.
5. Run your program and verify that the player is choosing randomly.
6. OK, now it's your turn. Prompt the user for their move. In the interest of consistency and simplicity, you should use the same encoding for this player in terms of what value means rock, what value means paper, and what value means scissors.
What should happen if the user inputs something that is outside the values for rock, paper, and scissors?
7. Each player has made a move; now let's see who won. First, pick a name, type, and initial value for the number of wins the random player has. Do the same for the human player.
Why do we need a variable to keep track of each player's wins? Why not keep track of only one player's wins and assume the other player won the other rounds?
8. In the loop, determine who won based on the current value of each player's move.
Use the rules of RPS to adjudicate the winner, and credit the win count properly.
9. After the loop completes, report the fraction of wins awarded to each of the two players.
10. Test your code by trying it with just one iteration, two iterations, and three iterations. Make sure it's working before you set it loose.
11. Run your code several times, each for multiple iterations.
12. Based on what you see, did one player tend to win more often than the other?

### Further investigations

• If you have time and interest, revise your program after demoing it so that both players are bots who choose randomly, or cycle through the choices in order. What happens?
• Investigate algorithms for playing RPS effectively.
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 2.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

TAs double check!
• This demo box is for extension 2.4
• The student has committed and pushed the work, and verified that it appears at bitbucket.

## Extension 5: Bank Interest Calculator (4 points):

Authors
• Brennan Morell
• Jarett Gross

#### Background

In this assignment, you have a balance in your bank account and you randomly either deposit or withdraw money from your account every day for one month (30 days). At the end of the month, you receive interest on your balance.

#### Procedure

1. Do your work for this extension in the bankinterest package. You will have to create a new class in that package to do the work below. Try to pick a good name for the class and use appropriate capitalization.
2. You start with \$4000 in your bank account and earn 2% interest at the end of the month.
3. Each day, you always withdraw or deposit money. Half of the time you withdraw \$100.00 and the other half of the time you deposit \$200.50.
How would you use random numbers to determine whether you withdraw or deposit money?
4. After withdrawing or depositing money, calculate your new balance. Then print the Day, Type, Amount, and Balance in a cleanly formatted table.
Since the cent is the lowest denomination in U.S. currency, round your withdrawals, deposits, and balance to the nearest cent.
5. Finally, after the 30th day, calculate and print the amount of interest you earned and your final balance.
Your final output should look similar to this:
```Day	Type		Amount		Balance
1	Deposit 	\$200.50		\$4200.50
2	Withdraw	\$100.00		\$4100.50
3	Deposit 	\$200.50		\$4301.00
4	Deposit 	\$200.50		\$4501.50
5	Withdraw	\$100.00		\$4401.50
6	Deposit 	\$200.50		\$4602.00
7	Withdraw	\$100.00		\$4502.00
8	Deposit 	\$200.50		\$4702.50
9	Withdraw	\$100.00		\$4602.50
10	Withdraw	\$100.00		\$4502.50
11	Deposit 	\$200.50		\$4703.00
12	Deposit 	\$200.50		\$4903.50
13	Deposit 	\$200.50		\$5104.00
14	Withdraw	\$100.00		\$5004.00
15	Withdraw	\$100.00		\$4904.00
16	Withdraw	\$100.00		\$4804.00
17	Deposit 	\$200.50		\$5004.50
18	Deposit 	\$200.50		\$5205.00
19	Deposit 	\$200.50		\$5405.50
20	Deposit 	\$200.50		\$5606.00
21	Withdraw	\$100.00		\$5506.00
22	Deposit 	\$200.50		\$5706.50
23	Deposit 	\$200.50		\$5907.00
24	Withdraw	\$100.00		\$5807.00
25	Deposit 	\$200.50		\$6007.50
26	Deposit 	\$200.50		\$6208.00
27	Deposit 	\$200.50		\$6408.50
28	Withdraw	\$100.00		\$6308.50
29	Withdraw	\$100.00		\$6208.50
30	Withdraw	\$100.00		\$6108.50

Interest earned: 122.17
Money after one month's interest: 6230.67
```
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 2.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

TAs double check!
• This demo box is for extension 2.5
• The student has committed and pushed the work, and verified that it appears at bitbucket.

## Extension 6: Mario (4 points):

Authors
• Nathan Vogt
• Elie Schramm

Mario, created in 1981 by Nintendo, is a classic video game starring the fictional Italian character Mario. In the assignment, loops printing hashtags will be used to build the block mountains as seen in the picture.

Create Mountain Blocks in Mario using loops. Test all your loops on mountains of various sizes.

This can be accomplished by printing each line or character separately, or by adding all the spaces and hashtags to one long String. Using "\n" in a String causes a line break. So, for example:
```String s = "one" + "\n" + "two";
```
prints out as:
```one
two
```

Hint: Use some character like a 0 for spacing the blocks correctly before substituting spaces. Also, if you're having trouble conceptualizing your code, we recommend drawing what is happening on paper.

• For this extension, create a Java class called Mario in the empty mario package of your extensions folder.
• You will have to demo all of the above patterns to the TA, so arrange for your program to conditionally do one of the patterns below, based on input that you provide when your program is run.
1. Mario runs from left to right. Create a mountain that he would have to climb, as shown in the example for a size 5 mountain. Think about the order in which the hashtags get printed.
with 0's Substituting spaces
```0000#              #
000##             ##
00###            ###
0####           ####
#####          #####
```
2. Create a mountain that he would descend, as shown.
```#
##
###
####
#####
```
3. Make a mountain that resembles the original mountain flipped upside down. Ex:
```#####
####
###
##
#
```
4. Make a mountain that resembles the second one upside down. Ex:
```#####
####
###
##
#
```
When you are done with this extension, you must be cleared by the TA to receive credit.
• Do a Team…Pull to update your repository. You must do this or the commit/push below may fail.
Make certain this has worked by logging into bitbucket. There you will see the commit(s) in your news feed if it was successful. You can also check the Source page to locate and ensure your code was received.

It is your responsibility to make certain the code has been pushed. Some of your work receives credit through testing of your pushed code. You will receive no credit for such work if you failed to push. We generally reserve the right to revoke credit for any of your work that has not been pushed on-time.

• Fill in the form below with the relevant information
• Have a TA check your work
• The TA should check your work and then fill in the TA's name
• Click OK while the TA watches
• If you request propagation, it does not happen immediately, but should be posted in the next day or so

This demo box is for extension 2.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