Towers of Hanoi

Here is a Java implementation of the classic Towers of Hanoi problem.

public class Hanoi {

	private static int moves = 0; // The number of moves made.

	/**
	 * Main method.
	 * @param args
	 */
	public static void main(String[] args) {
		solve(4, 1, 3);
	}

	/**
	 * Moves n disks from the startPeg to the endPeg, following
	 * the rules of the Towers Of Hanoi.
	 *
	 * @param n
	 * @param startPeg
	 * @param endPeg
	 */
	public static void solve(int n, int startPeg, int endPeg) {

		// Base case.
		if (n== 0){
			return;
		}

		// Define the temp peg.
		int tempPeg = 6 - startPeg - endPeg;

		// Recursive step.
		solve(n-1, startPeg, tempPeg);
		printMove(n, startPeg, endPeg); // Print what we moved.
		solve(n-1, tempPeg, endPeg);
	}

	/**
	 * Prints the movement of the disk from a peg to another peg.
	 *
	 * @param disk
	 * @param fromPeg
	 * @param toPeg
	 */
	private static void printMove(int disk, int fromPeg, int toPeg)
	{
		// Increment the move count.
		moves++;
		// Print the move.
		System.out.println("Move disk " + disk + " from peg " + fromPeg + " to peg " + toPeg + " | Move #: " + moves); // Print what we moved.
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *