/* * Laura Toma * csci 210 * * This is a program that solves the Towers-of-Hanoi puzzle. */ import java.util.Scanner; public class Hanoi { private Peg peg1; private Peg peg2; private Peg peg3; private int n; // how many disks public Hanoi() { // Get the number of disks System.out.println("How many disks would you like? (positive number)"); Scanner r = new Scanner(System.in); // for reading n = r.nextInt(); assert(n >= 1); //create the 3 pegs peg1 = new Peg(n, "A"); peg2 = new Peg(n, "B"); peg3 = new Peg(n, "C"); // fill up the source peg with disks. A disk is just an // integer representing the size of the disk for (int i = n; i > 0; i--) peg1.addLast(i); } //start the game public void solve() { System.out.println("-------------------------------"); System.out.println("GOAL: move " + n + " disks from " + peg1.getName() + " to " + peg2.getName()); System.out.println("Pegs at start:"); peg1.print(); peg2.print(); peg3.print(); System.out.println("Here is the sequence of moves:"); System.out.println("-------------------------------"); move(peg1, peg2, peg3, n); System.out.println("\nPegs at end:"); peg1.print(); peg2.print(); peg3.print(); } public static void main(String args[]) { //start a new game Hanoi hanoi = new Hanoi(); // solve it hanoi.solve(); //that's it System.out.println("Done."); } //moves the top d disks from source to dest using tmp as //intermediate peg and print the sequence of moves public void move(Peg source, Peg dest, Peg tmp, int d) { //base case: if one disk left, move it and stop if (d==1) { //correctness invariant: source peg must have at least one disk assert(source.getSize() >= 1); //print the move System.out.println("Move disk " + source.getLast() + " from " + source.getName() + " to " + dest.getName()); //perform the actual move int disk = source.deleteLast(); //correctness invariant: this disk must be smaller than //the top disk of dest assert(dest.isEmpty() || disk < dest.getLast()); dest.addLast(disk); } //more than 1 disks: recurse else { //move d-1 disks from source to tmp move(source, tmp, dest, d-1); //move bottom disk from source to dest move(source, dest, tmp, 1); //move d-1 disks from tmp to dest move(tmp, dest, source, d-1); } } }