In: Computer Science
Tower of Hanoi - Java Code
Example output
Tower of Hanoi Program by YOUR NAME Enter Starting Rod (A, B, or C): A Enter Ending Rod (A, B, or C): A Sorry. starting and ending rod cannot be the same. Enter Ending Rod ((A, B, or C): C OK Starting with discs 1, 2, and 3 on rod A Moves are as follows: 1. Move disc 1 from rod A to rod C 2. Move disc 2 from rod A to rod B 3. Move disc 1 from rod C to rod B 4. Move disc. 3 from rod A to rod C 5. Move disk 1 from rod B to rod A 6. Move disk 2 from rod B to rod C 7. Move disk 1 from rod A to rod C All done. Took a total of 7 moves.
Hello,
Code:
import java.util.Scanner;
public class TOH
{
// Recursive function to solve Tower of Hanoi
static int towerOfHanoi(int n, String start_rod, String end_rod, String aux_rod, int moves)
{
if(n>0){
if (n == 1)
{
System.out.println("Move disk 1 from rod " + start_rod + " to rod " + end_rod);
return moves;
}
moves = towerOfHanoi(n-1, start_rod, aux_rod, end_rod, moves);
System.out.println("Move disk " + n + " from rod " + start_rod + " to rod " + end_rod);
moves ++;
moves = towerOfHanoi(n-1, aux_rod, end_rod, start_rod, moves);
moves ++;
}
return moves;
}
// Main method
public static void main(String args[])
{
// Take start and end rod as input from the user
Scanner scanner = new Scanner (System.in);
System.out.print("Enter Starting Rod (A, B, or C): ");
String start_rod = scanner.next().toUpperCase();
System.out.println(start_rod);
System.out.print("Enter Ending Rod (A, B, or C): ");
String end_rod = scanner.next().toUpperCase();
System.out.println(end_rod);
// Check if the user enters same start and end rod
while (start_rod.equals(end_rod))
{
System.out.println("Sorry. starting and ending rod cannot be the same. ");
System.out.print("Enter Ending Rod (A, B, or C): ");
end_rod = scanner.next().toUpperCase();
System.out.println(end_rod);
}
// Finding the aux rod
String aux_rod;
if ((start_rod.equals("A") && end_rod.equals("C")) || (start_rod.equals("C") && end_rod.equals("A")))
{
aux_rod = "B";
}
else if ((start_rod.equals("B") && end_rod.equals("C")) || (start_rod.equals("C") && end_rod.equals("B")))
{
aux_rod = "A";
}
else
{
aux_rod = "C";
}
int n = 3; // Number of disks as defined in the question
int moves = 1; // Minimum number of moves to count the number of steps taken.
int count = towerOfHanoi(n, start_rod, end_rod, aux_rod, moves);
System.out.println("All done. Took a total of " + count + " moves");
}
}
Code Snippet:
Output:
$javac TOH.java $java -Xmx128M -Xms16M TOH Enter Starting Rod (A, B, or C): A Enter Ending Rod (A, B, or C): A Sorry. starting and ending rod cannot be the same. Enter Ending Rod (A, B, or C): B Move disk 1 from rod A to rod B Move disk 2 from rod A to rod C Move disk 1 from rod B to rod C Move disk 3 from rod A to rod B Move disk 1 from rod C to rod A Move disk 2 from rod C to rod B Move disk 1 from rod A to rod B All done. Took a total of 7 moves