created 01/24/99; revised 07/31/07, 10/20/08

# Chapter 20 Programming Exercises

## Exercise 1 — Guessing Game

Write a program that implements a guessing game. This is a "classic" program, frequently assigned in CS 1 classes.

The program picks a random number from 1 to 10. Now the user gets three guesses. As soon as the user enters the correct number the program writes a winning message and exits. If the user fails to enter the correct number in three guesses, the program writes a failure message and exits.

Use methods of the `Random` class. Here are two example runs of the program:

```C:\>java GuessingGame

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
wrong
8
RIGHT!
You have won the game.

C:\>java GuessingGame

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
1
wrong
5
wrong
9
wrong
The correct number was 7.
You have lost the game.
```

## Exercise 2 — Improved Guessing Game

Write a more complicated guessing game, similar to the one in Exercise 1, but now the program is to write "cold" when the guess is 3 or more away from the correct answer, "warm" when the guess is 2 away, and "hot" when the guess is 1 away. As soon as the user enters the correct number the program writes a winning message and exits. For example:

```C:\>java GuessingGame

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
1
cold
5
RIGHT!
You have won the game.

C:\>java GuessingGame

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
cold
5
cold
8
wrong.
The correct number was 9.
You have lost the game.

C:\>java GuessingGame
I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
hot
5
warm
3
RIGHT!
You have won the game.
```

## Exercise 3 — Further Improved Guessing Game

Write an even more complicated guessing game. In this version, the full game consists of 10 "rounds," where each round is a game like exercise 2. After the 10 rounds, the program prints out how many of the 10 rounds were won and how many were lost.

• players who win 7 or fewer rounds are rated as "amateurs,"
• players who win 8 rounds are rated as "advanced,"
• players who win 9 rounds are rated as "professionals," and
• players who win all 10 rounds are rated as "hackers."

Here is an example run:

```C:\>java GuessingGame

round 1:

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
4
hot
5
RIGHT!
You have won 1 out of 1 rounds.

round 2:

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
10
cold
5
cold
3
wrong
The correct number was 1
You have won 1 out of 2 rounds.

. . .

round 10:

I am thinking of a number from 1 to 10.
You must guess what it is in three tries.
Enter a guess:
1
cold
6
warm
8
RIGHT!
You have won 7 out of 10 rounds.

C:\>java GuessingGame
```

## Exercise 4 — Password Generator

This exercise is based on the PasswordGenerator program in the chapter.

To improve the password, edit the string of characters `choices` so that it contains more digits, increasing the chances that digits will be picked. Do this by appending "1234567890" several more times on to the end of `choices`. There is no need for `choices` to contain only one of each character. If you want punctuation your passwords, append those characters to the string, as well.

Another improvement is to require that a password have at least one digit. There are several ways in which this can be done. Don't assume that the required digit in a password will be in a fixed location.

A further improvement is the rule that every consonant must be followed by a vowel of the same case. This will make passwords easier to memorize. Of course, it also makes them easier to guess, especially if a cracker knows that this rule is being used.

## Exercise 5 — Password Cracker

A password generator can also be used as a password cracker. Essentially, the generator keeps creating passwords until it finds one that works. (It is for this reason that most applications reject a logon attempt if the password fails three times.)

Write a program that asks the user for a password. The user enters a password (which must be short). Now pretend that this password is a secret from the rest of the program, which must try to guess it. The program then uses the password generator repeatedly until a randomly generated password matches the password the user entered. Assume that the user's password is five characters or less (otherwise this program will never end). Write out the number attempts it took to find the password. Here are some example runs:

```K:\cai\>java PasswordCracker
It took 2181892 tries to guess it

It took 10956100 tries to guess it

It took 91555945 tries to guess it

It took 279530402 tries to guess it
```

A better cracker program would systematically generate all possible one-letter passwords, then all possible two-letter passwords, then all possible three-letter passwords,..., and so on, comparing each one to the secret password. This program is hard to write without arrays (a subject of a future chapter).

## Exercise 6 — 1D Random Walk

A one dimensional random walk is where a particle starts out at X=0.0, then moves right or left along the X axis by random amounts. Think of it as a bead an a string, randomly being shaken back and forth.

Write a program that initializes to zero a variable `X`, representing the position of the bead, then repeatedly adds random amounts in the range (-1.0, +1.0) to `X`. The program stops after a specified number of iterations. You will need to use the `nextDouble()` method of `Random` and transform it to match the specified range.

How distant from its starting position is `X` after 100 iterations? 1000? What is the maximum distance it coule be? How likely is that?

```
K:\cai\>java RandomWalkOneDim
How many iterations?
100
After 100 moves X is now at 1.1190381131949723

K:\cai\>java RandomWalkOneDim
How many iterations?
1000
After 1000 moves X is now at -0.4633309201402265
```

Change the program so that it keeps iterating until the bead reaches a particular distance (positive or negative) from the origin. Use `Math.abs()` to determine the distance. If you pick a large distance, you may have to kill the running program, since the distance may never be reached. (On Windows systems, do this with control-D in the DOS window.)

## Exercise 7 — 2D Random Walk

A two dimensional random walk is where a particle starts out at X=0.0, Y=0.0 then moves by small random increments in both X and Y. Think of it as a confused ant, randomly walking on the 2D plane.

Write a program that initializes to zero two variables `X` and `Y`, representing the position of the ant, then repeatedly adds random amounts in the range (-1.0, +1.0) to each of them. Pick two random amounts, one for `X` and one for `Y`. The program stops after a specified number of iterations and prints out the values of the coordinates and the final distance of the ant from the origin. Use the Pythagorean formula to calculate the distance:

```             _______
distance = \/X2 + Y2
```

There are plenty of variations on this program, for instance, counting the iterations it takes to reach a certain distance. Or, implement two ants, each with its own coordinates, which both start out at (0, 0) and wander for 1000 steps. How far apart are the ants? If one ant does not move, will they be closer or further apart than when they both move?

Of course, another variation is to implement a 3D random walk, with independent variables `X`, `Y`, and `Z`. Think of this as a confused firefly, fluttering randomly through the night.

## Exercise 8 — Square Root Game

Write a program that implements a two player game. The computer is the score keeper and the two players are humans. Each round of the game starts with the computer randomly picking a double precision number from 1.0 to slightly less than 100.0. Each player estimates the square root of the number and enters the estimate. The player who's estimate is closest to correct wins the round. Players alternate who goes first in each round. Play ends after a specified number of rounds.

```How many rounds? 4

What is the square root of 83.29097831183603   ?
The correct square root: 9.126389116832353
Dweezle is 0.026389116832353565 away
Moon Unit is 0.07361088316764608 away
Dweezle wins!

What is the square root of 87.79346957866132   ?
The correct square root: 9.36981694477866
Dweezle is 0.46981694477866043 away
Moon Unit is 0.5698169447786601 away
Dweezle wins!

What is the square root of 67.44682032701256   ?
The correct square root: 8.212601313044033
Dweezle is 0.012601313044033446 away
Moon Unit is 0.11260131304403309 away
Dweezle wins!

What is the square root of 71.64725527288849   ?
The correct square root: 8.464470170831042
Dweezle is 0.01447017083104285 away
Moon Unit is 0.06447017083104178 away
Dweezle wins!

---- Final Score ----
Dweezle:  4   Moon Unit:  0
```

Call `Scanner.nextLine()` to read in the end of line characters after the number of iterations. Then read in the player names using `Scanner.nextLine()`. Use `nextDouble()` for the estimates. `Math.abs()` and `Math.sqrt()` will be useful.

## Exercise 9 — Pig-like Dice Game

This is a dice game similar to the game Pig, but easier to implement. The player plays against the computer.

1. Player and Computer start out with zero points.
2. The winner is the first player to reach 100 points or more.
3. In each round, the computer rolls first, followed by the player.
4. The computer rolls three dice and the sum of spots is added to its score.
5. At the start of the player's turn, a working sum is initialized to zero.
6. The player then rolls a single die as many times as desired.
• If the die shows a 1 (on the first roll or any roll), then the player's turn is over and nothing is added to the player's score.
• For rolls other than 1, the roll is added to the working sum.
• If the player stops rolling before a 1 occurs, then the working sum is added to the player's score.

In a genuine Pig game, the computer would repeatedly throw a single die (just like the player) and use strategy to determine when to stop.