1 import java.util.Arrays;
2
3 /**
4 A Towers of Hanoi puzzle with three towers.
5 */
6 public class TowersOfHanoi
7 {
8 private Tower[] towers;
9
10 /**
11 Constructs a puzzle in which the first tower has a given number of disks.
12 @param ndisks the number of disks
13 */
14 public TowersOfHanoi(int ndisks)
15 {
16 towers = new Tower[3];
17 towers[0] = new Tower(ndisks);
18 towers[1] = new Tower(0);
19 towers[2] = new Tower(0);
20 }
21
22 /**
23 Moves a pile of disks from one peg to another and displays the movement.
24 @param disks the number of disks to move
25 @param from the peg from which to move the disks
26 @param to the peg to which to move the disks
27 */
28 public void move(int disks, int from, int to)
29 {
30 if (disks > 0)
31 {
32 int other = 3 - from - to;
33 move(disks - 1, from, other);
34 towers[to].add(towers[from].remove());
35 System.out.println(Arrays.toString(towers));
36 move(disks - 1, other, to);
37 }
38 }
39 }
40