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


Chapter 30 Programming Exercises


Exercise 1 — Guessing Game

Write a program that implements a guessing game. This is a "classic" program, frequently assigned in beginning CS 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.

Click here to go back to the main menu.


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.

Click here to go back to the main menu.


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.

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.

Your rating: amateur.

C:\>

Click here to go back to the main menu.


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.

Click here to go back to the main menu.


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 the program will run for eons). Write out the number attempts it took to find the password. Here are some example runs:

K:\cai\>java PasswordCracker
Enter a "secret" password-->ant
Here is your password: ant
It took 2181892 tries to guess it

K:\cai\>java PasswordCracker
Enter a "secret" password-->rats
Here is your password: rats
It took 10956100 tries to guess it

K:\cai\>java PasswordCracker
Enter a "secret" password-->frog
Here is your password: frog
It took 91555945 tries to guess it

K:\cai\>java PasswordCracker
Enter a "secret" password-->moose
Here is your password: moose
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).

Click here to go back to the main menu.


Exercise 6 — Average of a Sample

The average of the 1000 integers from 0 to 1000 is 500. The the integers 0 to 499 are on one side of 500 and the integers 501 to 1000 are on the other sided. So the average of a sample of integers randomly selected from the range [0,1000] should be about 500.

Write a program that asks the user for N and then computes the average of N integers selected from [0,1000]. Note that both zero and one thousand are included in the range. Compute the average as a double precision value. Of course, each time you run the program for the same N you will most likely get a different result.

Run the program for different values of N (and several times for each N) and observe how close the values are to 500. Random may generate the same values more than once, so even if N is 1000 the average will not be exactly 500.

Click here to go back to the main menu.


Exercise 7 — 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. Note that X can be negative or positive (or zero). 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.)

Click here to go back to the main menu.


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.

Click here to go back to the main menu.


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
First Player, sign in--> Dweezle
Secnd Player, sign in--> Moon Unit

What is the square root of 83.29097831183603   ?
Dweezle, your guess: 9.1
Moon Unit, your guess: 9.2
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   ?
Moon Unit, your guess: 8.8
Dweezle, your guess: 8.9
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   ?
Dweezle, your guess: 8.2
Moon Unit, your guess: 8.1
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   ?
Moon Unit, your guess: 8.4
Dweezle, your guess: 8.45
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.

Click here to go back to the main menu.


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.

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.

Click here to go back to the main menu.