Docsity

TOWER OF HANOI USING STACKS EASY CODE IN JAVA WITH AND WITHOUT JUNIT TESTING, Lab Reports of Data Structures and Algorithms

Toggle sidebar
bg1
The Tower of Hanoi
The Tower of Hanoi is a game that has a very elegant recursive solution. The goal is to move all
rings of tower A to tower B:
However, you must adhere to the following rules
• you can only move one ring at a time
• you can only move the top ring
• you cannot put a larger ring on top of a smaller ring
To better understand the game, there are several places online where you can play it. For
example, here:
http://www.mathsisfun.com/games/towerofhanoi.html
Your job is to implement a recursive method that solves the game for n number of rings.
You will see how the game is played in the test/HanoiTest.java file, i.e.
Hanoi game = new Hanoi(rings);
game.playHanoi();
Where rings is an integer value which is the number of rings starting on tower A.
A template for your implementation is in the file Hanoi.java.
Q2A) Implement moving one ring
You should implement moving one ring by implementing the method:
public static void moveOneRing(int from, int to){
/* TODO */
}
Where integers from and to represent indexes: 0 for tower A, 1 for tower B and 2 for tower
C.
To simulate the move of a ring from one tower to another, update the stacks stored in the
towers array variable in Hanoi.java, which stores one stack for each of the 3 towers. Hanoi
stacks A, B and C are implemented with this array in Hanoi.java as follows:
private Stack[] towers = new Stack[TOWERS];
Where towers[0] is a Stack data structure that represents Hanoi tower A. In other words,
there is a Stack data structure at position 0 in the array towers. This means that towers[1]
is a Stack for Hanoi tower B, towers[2]is a Stack for Hanoi tower C.
If you want to place a ring on top of a Hanoi tower, you’ll need to push a ring onto the Stack
data structure that represents that Hanoi tower.
For example, to place a ring called ring onto Hanoi tower B:
towers[1].push( ring );
The idea is to take a ring from the top of the from tower (where from is an array index
position) and put it on the top of the to tower.
The tests are not expected to pass at this point.
Q2B) Implementing moving a pile
You are to implement the Hanoi game in a recursive programming style. The movePile
method should coordinate the order of calls to moveOneRing that you implemented for the
previous question. The sequencing of moveOneRing calls should stick to the rules of the
Hanoi game and should successfully move all rings from the from tower to the to tower. The
next page shows an example of moving three rings from tower A to tower B.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download TOWER OF HANOI USING STACKS EASY CODE IN JAVA WITH AND WITHOUT JUNIT TESTING and more Lab Reports Data Structures and Algorithms in PDF only on Docsity!

The Tower of Hanoi

The Tower of Hanoi is a game that has a very elegant recursive solution. The goal is to move all

rings of tower A to tower B:

However, you must adhere to the following rules

• you can only move one ring at a time

• you can only move the top ring

• you cannot put a larger ring on top of a smaller ring

To better understand the game, there are several places online where you can play it. For

example, here:

http://www.mathsisfun.com/games/towerofhanoi.html

Your job is to implement a recursive method that solves the game for n number of rings.

You will see how the game is played in the test/HanoiTest.java file, i.e.

Hanoi game = new Hanoi(rings);

game.playHanoi();

Where rings is an integer value which is the number of rings starting on tower A.

A template for your implementation is in the file Hanoi.java.

Q2A) Implement moving one ring

You should implement moving one ring by implementing the method:

public static void moveOneRing(int from, int to){

/* TODO */

Where integers from and to represent indexes: 0 for tower A, 1 for tower B and 2 for tower

C.

To simulate the move of a ring from one tower to another, update the stacks stored in the

towers array variable in Hanoi.java , which stores one stack for each of the 3 towers. Hanoi

stacks A, B and C are implemented with this array in Hanoi.java as follows:

private Stack[] towers = new Stack[TOWERS];

Where towers[0] is a Stack data structure that represents Hanoi tower A. In other words,

there is a Stack data structure at position 0 in the array towers. This means that towers[1]

is a Stack for Hanoi tower B, towers[2]is a Stack for Hanoi tower C.

If you want to place a ring on top of a Hanoi tower, you’ll need to push a ring onto the Stack

data structure that represents that Hanoi tower.

For example, to place a ring called ring onto Hanoi tower B:

towers[1].push( ring );

The idea is to take a ring from the top of the from tower (where from is an array index

position) and put it on the top of the to tower.

The tests are not expected to pass at this point.

Q2B) Implementing moving a pile

You are to implement the Hanoi game in a recursive programming style. The movePile

method should coordinate the order of calls to moveOneRing that you implemented for the

previous question. The sequencing of moveOneRing calls should stick to the rules of the

Hanoi game and should successfully move all rings from the from tower to the to tower. The

next page shows an example of moving three rings from tower A to tower B.

The 2nd part requires movePile to be implemented:

public void movePile(int n, int from, int to, int via){ /* TODO */ }

In the playHanoi() method it is used like this:

movePile(numRings,0,1,2);

Where numRings are the number of rings initially on tower A.

The movePile method should be a recursive implementation.

  • Base case : when n == 1, move the one ring on tower with index from, to the tower with

index to.

  • Step case : use recursive calls to move n rings from tower from to tower to. Coordinate

these moveOneRing calls (passing the correct from and to arguments), using recursive

calls inside movePile.

See the Javdoc documentation for the movePile method in Hanoi.java for an execution

example.

Hint 4 explains the algorithm in more detail.

The tests in HanoiTests.java runs the game using 1, 2.. 10 and 20 rings starting at tower A. Each

time the end of game should result in all rings on tower B, and no rings on towers A and C.

During execution, at no time can a larger ring be placed on top of a smaller ring. The

checkTower method ensures this invariant. If it is ever violated, a HanoiException is

thrown.

// hanoi.java class HanoiException extends RuntimeException { public HanoiException(String err) { super(err); } } public class Hanoi { /*

  • Part4: Tower of Hanoi / // our game will always use 3 Hanoi towers //an array whose type is stack and on diff index numbers, stack are stored, actually stacks act as tower private final int TOWERS = 3 ; private Stack[] towers = new Stack[TOWERS]; private int numRings; /*
  • Initialises the Hanoi towers.
  • @param numRings how many rings to involve in the game. */ public Hanoi(int numRings) { this.numRings = numRings; // initialise each tower as a stack, which a capacity matching // the number of rings in the game.
  • {@link #checkTower(int)} and the JUnit tests in HanoiTest.java.
  • For example, to play with 3 rings, moving them all from tower A to tower B,
  • the valid execution is:
  • *
     * moveOneRing(0,1) * moveOneRing(0,2) * moveOneRing(1,2) * moveOneRing(0,1) * moveOneRing(2,0) * moveOneRing(2,1) * moveOneRing(0,1) * 
    * * where 0 is tower A, 1 is tower B, 2 is tower C. * * @param n a counter that, when n==1 means we've removed all rings above the * bottom ring * @param from the index of the tower to move all rings from * @param to the index of the tower to move all rings to * @param via the index of the tower which intermediate rings will be moved to */ //from is the source tower, to is the destination and via is the helper tower public void movePile(int n, int from, int to, int via) { if (n == 1 ) { moveOneRing(from, to); } else { movePile(n- 1 , from, via, to); moveOneRing(from, to); movePile(n- 1 , via, to, from); } } /** * @param i the index of the tower, starting indexing at 0. * @return the Hanoi stack. */ public Stack getTower(int i) { return towers[i]; } public void playHanoi() { /// move all rings from tower A (0), to tower B (1), via tower C (2)

movePile(numRings, 0 , 1 , 2 ); } /**

  • After each ring move, check the invariant that every ring is larger than all
  • rings stacked higher on the same tower.
  • @param towerIndex the tower to check this invariant. / //function to check larger ring should not be placed on the smaller ring private void checkTower(int towerIndex) { Stack ringsCopy = (Stack) towers[towerIndex].clone(); int ringOnTopSize = - 1 ; while (!ringsCopy.isEmpty()) { Ring nextRing = (Ring) ringsCopy.pop(); if (nextRing.getRingSize() < ringOnTopSize) { throw new HanoiException("a smaller ring is beneath a larger ring on tower " + towerIndex); } ringOnTopSize = nextRing.getRingSize(); } } } /*
  • Simulates a Hanoi ring moved between Hanoi towers. */ class Ring { // The size of a ring, where the larger the integer value for 'size', // the larger the ring. private int size; public Ring(int size) { this.size = size; } public int getRingSize() { return size; } } Hanoi Test with main method if junit test is not used else junit test is also available public class HanoiTest { public static void main(String[] args) {

@Test public void playSixRings() { playNRings(6); } @Test public void playSevenRings() { playNRings(7); } @Test public void playEightRings() { playNRings(8); } @Test public void playNineRings() { playNRings(9); } @Test public void playTenRings() { playNRings(10); } @Test public void playTwentyRings() { playNRings(20); } /**

  • Play the Hanoi tower game with a given number of rings.
  • Tower A has index 0, Tower B has index 1, Tower C has index 2
  • @param rings the number of rings to play in the game. */ public void playNRings(int rings) { Hanoi game = new Hanoi(rings); game.playHanoi(); // ensure tower A is empty assertEquals(0, game.getTower(0).size()); // ensure tower B is full assertEquals(rings, game.getTower(1).size()); // ensure tower C is empty assertEquals(0, game.getTower(2).size()); } } //stack class for Hanoi class StackException extends RuntimeException{ public StackException(String err) { super(err); } } public class Stack implements Cloneable { private Object[] S; private int top; private int capacity; private static int DEFAULT_SIZE = 100000; public Stack( int size){

capacity = size; S = new Object[size]; top = -1; } public Stack(){ this(DEFAULT_SIZE); } public boolean isEmpty(){ return top < 0; } public int size(){