Question
Description: Based on Chapter 3, Programming Problem 12 The game Towers of Hanoi consists of three pegs and a collection of rings that stack on
Description:
Based on Chapter 3, Programming Problem 12
The game Towers of Hanoi consists of three pegs and a collection of rings that stack on the pegs. The rings are different sizes. The initial configuration for a five-ring game is shown here, with the first tower having rings from one inch (on the top) to five inches (on the bottom).
The rings are stacked in decreasing order of their size, and the second and third towers are initially empty. During the game, the child may transfer rings one at a time from the top of one peg to the top of another. The goal is to move all the rings from the first peg to the second peg. The difficulty is that the child may not place a ring on top of one with a smaller diameter. There is the one extra peg to hold rings temporarily, but the prohibition against a larger ring on a smaller ring applies to it as well as to the other two pegs.
Assignment:
Create a Towers class that implements the game Towers of Hanoi with three pegs.
Feature | Signature | Requirement |
Constructors | Towers(n) | Precondition: 1 Postcondition: The towers have been initialized with n rings on the first peg and no rings on the other two pegs. The diameters of the first peg's rings are from one inch (on the top) to n inches (on the bottom). |
| Towers() | Creates a default-sized Towers with n = 5 |
Methods | int getRingCount(int pegNumber) | Precondition: pegNumber is 1, 2, or 3. Postcondition: The return value is the number of rings on the specified peg.
|
| int getTopDiameter (int pegNumber) | Precondition: pegNumber is 1, 2, or 3. Postcondition: If getRingCount(pegNumber) > 0, then the return value is the diameter of the top ring on the specified peg; otherwise, the return value is zero. |
| boolean move(int startPeg, int endPeg) | Precondition: startPeg is a peg number (1, 2, or 3), and getRingCount(startPeg) > 0; endPeg is a different peg number (not equal to startPeg), and if endPeg has at least one ring, then getTopDiameter(startPeg) is less than getTopDiameter(endPeg). Postcondition: If precondition is not true, return value is false and pegs are unchanged, otherwise the top ring has been moved from startPeg to endPeg and return value is true. |
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started