![]() |
CS 111 - Introduction to Computer Science
Homework #5 |
1. Gas Mileage: Exercise 4.17. Call your class Mileage.java. Place your pseudocode in a block comment. Let a user's input of 0 miles driven serve as the sentinel value marking the end of input. Your test cases should be in plain text files named mileage1.dat, mileage2.dat, and mileage3.dat, such that entering a command of the form "java Mileage < testFileName" will execute your mileage computation with the given testFileName as input data.
2. Largest: Exercise 4.21. Call your class Largest.java. Place your pseudocode in a block comment. Don't forget that the largest value can be negative.
3. Optimal Piglet Advisor: Here is a description of a simple coin game called Piglet. (Piglet is based on a simple dice game called Pig.):
The object of Piglet is to be the first player to reach n points. (In this case, we'll use n = 6.) Each turn, a player repeatedly flips a coin until either a "tail" is flipped or the player holds. At any time during the player's turn, the player is faced with two choices: flip or hold. If the coin turns up tails, the player scores nothing for the turn and it becomes the opponent's turn. Otherwise, the player's turn continues. If the player chooses to hold, the number of consecutively flipped heads is added to the player's score and it becomes the opponent's turn.
Below is a table that describe the optimal way to play Piglet when the goal score is 6. The way you read the table is as follows: The rows are numbered 0 to 5 downward. The columns are numbered 0 to 5 rightward. If your score is i and your opponent's score is j, then the number at row i, column j is the number of consecutive heads at which you should hold. Otherwise, keep flipping.
Your task is to create an optimal Piglet advisor. Call your program PigletAdvisor.java. Use a Scanner to ask the user for (1) their score, and (2) their opponent's score. If the score(s) are invalid, the output "Invalid scores". Otherwise, the output should be "You should hold after # heads.", where # is given in the above table and "heads" is properly singular or plural depending on #.
Hint: There is no need to store a table (e.g. 2D array introduced later) if you notice that the table can be divided into cases: (1) either player has 5 points or the sum of the scores is 7 or more and you need to try to win this turn, (2) players each have exactly three points and you should hold at 1 head, (3) you're even or behind and should hold at 2, and (4) otherwise, you should hold at 1. These cases should be handled in this order using an if-else chain to determine the hold value.