-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTower.java
More file actions
36 lines (31 loc) · 1009 Bytes
/
Copy pathTower.java
File metadata and controls
36 lines (31 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Tower{
int towerNum;
StackImplementationWithArray discs;
Tower(int towerNum,int numberOfDiscs)
{
this.towerNum=towerNum;
discs=new StackImplementationWithArray(numberOfDiscs);
}
public void addDisc(int data) throws Exception
{
if (!(this.discs.isEmpty()) && this.discs.peek()<=data)
System.out.println("Error placing disc since it is larger than the top disc");
else
discs.push(data);
}
public void moveDiscs(int numberOfDiscs,Tower origin,Tower buffer,Tower destination) throws Exception
{
if (numberOfDiscs>0)
{
this.moveDiscs(numberOfDiscs-1,origin,destination,buffer);
moveLastDisc(origin,destination);
buffer.moveDiscs(numberOfDiscs-1, buffer, origin, destination);
}
}
public void moveLastDisc(Tower origin,Tower destination) throws Exception
{
int disc=origin.discs.pop();
destination.addDisc(disc);
System.out.println("Moved disc "+disc+" from tower "+origin.towerNum+" to Tower "+destination.towerNum);
}
}