class TowerOfHanoi { class Peg { String name; int[] disks = new int[10]; int topDisk=-1; // topDisk indexes the topMost disk. /* We give each peg a name, and an initial number of * disks, whose size is decreasing */ Peg(String name, int numberOfDisks){ this.name = name; while( numberOfDisks > 0 ){ addOnTop(numberOfDisks); numberOfDisks--; } System.out.println("Peg " + name + " initialized with " + (topDisk+1)); } /* Add disk of specified size to this peg */ public void addOnTop(int disk){ if (topDisk >= 0 && disk >= disks[topDisk]) throw new IllegalArgumentException("cheater"); topDisk++; disks[topDisk] = disk; } /* remove the top disk from this peg * return the size of the removed disk */ public int removeTop(){ int top = disks[topDisk]; disks[topDisk] = 0; topDisk--; return top; } /* move the top disk to the target peg */ public void moveTopTo(Peg targetPeg){ int disk; disk = removeTop(); targetPeg.addOnTop(disk); System.out.println("moved " + disk + " from peg " + this.name + " to " + targetPeg.name); } /* move the topmost N disks to the target peg * the auxiliary (aux) peg is used as helper in this process */ public void moveN(int N, Peg target, Peg aux){ if (N > 0){ moveN(N-1, aux, target); moveTopTo(target); aux.moveN(N-1, target, this); } } } private Peg a,b,c; public TowerOfHanoi(int numberOfDisks){ a = new Peg("A", numberOfDisks ); b = new Peg("B", 0); c = new Peg("C", 0); a.moveN(numberOfDisks , c, b); } public static void main(String[] args){ new TowerOfHanoi(3); } }