Java code Create a class Towers that implements the game Towers of Hanoi with th
ID: 3902728 • Letter: J
Question
Java code Create a class Towers that implements the game Towers of Hanoi with three pegs. Feature Signature Requirement Constructors Towers(rings) Precondition: 1 <= rings <= 64; 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 and endPeg must be > 0 and <=3; Validity Rules: startPeg is not empty startPeg != endPeg endPeg is empty or (topDiameter(startPeg) < topDiameter(endPeg)) Postcondition: If move is valid the top ring has been moved from startPeg to endPeg and return value is true, otherwise pegs are unchanged and return value is false
Explanation / Answer
Given below is the code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
public class Towers {
private int rings;
private int[][] towers;
private int[] numRings;
public Towers()
{
this(5);
}
public Towers(int rings)
{
this.rings = rings;
towers = new int[3][rings];
for(int i = rings-1, j = 1; i >= 0; i--, j++)
towers[0][i] = j;
numRings = new int[3];
numRings[0] = rings;
}
int getRingCount(int pegNumber)
{
if(pegNumber >= 1 && pegNumber <= 3)
return numRings[pegNumber-1];
else
return 0;
}
int getTopDiameter(int pegNumber)
{
if(getRingCount(pegNumber) > 0)
{
int index = getRingCount(pegNumber) - 1;
return towers[pegNumber - 1][index];
}
else
return 0;
}
boolean move(int startPeg, int endPeg)
{
if(startPeg > 0 && startPeg <= 3 && endPeg > 0 && endPeg <= 3 &&
startPeg != endPeg && getRingCount(startPeg) != 0 &&
(getRingCount(endPeg) == 0 || getTopDiameter(startPeg) < getTopDiameter(endPeg)))
{
int index1 = getRingCount(startPeg) - 1; //from which to get
int index2 = getRingCount(endPeg); //where to move
//move the ring
towers[endPeg - 1][index2] = towers[startPeg - 1][index1];
//update the top indices
numRings[startPeg - 1]--;
numRings[endPeg - 1]++;
return true;
}
else
return false;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.