Question

In: Computer Science

Tower of Hanoi - Java Code Use three rods labeled A, B, and C Use three...

Tower of Hanoi - Java Code

  • Use three rods labeled A, B, and C
  • Use three discs labels 1 (smallest), 2 (medium size), and 3 (largest disc)
  • The program prompts you to enter the starting rod (A, B, or C)
  • The program prompts you to enter the ending rod (A, B, or C, but cannot be same rod as entered as starting rod)
  • The starting rod has discs 1, 2, 3, where 1 is on top of 2 is on top of 3 (just like we covered in class)
  • Your program should print out each move, showing clearly which disc goes from/to. See trace below.

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.

Solutions

Expert Solution

Hello,

  • The program has been implemented below in Java.
  • The error handling cases have been taken care of.
  • Appropriate comments have been added for better understanding of the user.
  • Below is the code, code snippet ( for indentation purposes) and output.

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

Related Solutions

Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use...
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use 4 disks and 3 bars
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include...
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include <stack> #include <string> #include <vector> using namespace std; class TowersOfHanoi { friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers); public: //constructor TowersOfHanoi(); //custom methods unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout); private: //custom methods void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux); //temporary variable unsigned _n_moves; //data const unsigned _n_towers; stack<unsigned>* _tower; }; #include "TowersOfHanoi.h" // ostream& operator<<(ostream& sink, const...
10. The Tower of Hanoi is a puzzle consisting of a board with three dowels and...
10. The Tower of Hanoi is a puzzle consisting of a board with three dowels and a collection of n disks of n different radii. The disks have holes drilled through their centers so they can fit on the dowels on the board. Initially, all the disks are on the first dowel arranged in order of their sizes, with the largest one being at the bottom, and the smallest one on the top. The object is to move all the...
Tower of Hanoi problem please use this code #pragma once #include #include #include #include using namespace...
Tower of Hanoi problem please use this code #pragma once #include #include #include #include using namespace std; class TowersOfHanoi { friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers); public: //constructor TowersOfHanoi(); //custom methods unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout); private: //custom methods void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux); //temporary variable unsigned _n_moves; //data const unsigned _n_towers; stack* _tower; }; #include "TowersOfHanoi.h" // ostream& operator<<(ostream& sink, const TowersOfHanoi& hanoi) { for (unsigned index =...
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there...
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there can be any amount of disks and there are either 3,4, or 5 pegs to store the disks(# of pegs and disks is manually inputted by user), in Tower of Hanoi game, the object of the game is move all the pieces from the 1st peg to the right most peg or the opposite side. You can place disks on top of each other...
Three flasks, labeled A, B, and C, contained aqueous solutions of the same pH. It was...
Three flasks, labeled A, B, and C, contained aqueous solutions of the same pH. It was known that one of the solutions was 1.0 × 10–3 M in nitric acid, one was 6 × 10–3 M in formic acid, and one was 4 × 10–2 M in the salt formed by the weak organic base aniline with hydrochloric acid (C6H5NH3Cl). (Formic acid is monoprotic.) (a) Describe a procedure for identifying the solutions. (b) Compare qualitatively (on the basis of the...
Consider the three electronic transitions in a hydrogen atom shown here, labeled A, B, and C....
Consider the three electronic transitions in a hydrogen atom shown here, labeled A, B, and C. (a) Three electromagnetic waves, all drawn on the same scale, are also shown. Each corresponds to one of the transitions. Which electromagnetic wave (i), (ii), or (iii), is associated with electronic transition C?(b) Calculate the energy of the photon emitted for each transition.(c) Calculate the wavelength of the photon emitted for each transition. Do any of these transitions lead to the emission of visible light?...
Please take this c++ code and make it into java code. /* RecursionPuzzleSolver * ------------ *...
Please take this c++ code and make it into java code. /* RecursionPuzzleSolver * ------------ * This program takes a puzzle board and returns true if the * board is solvable and false otherwise * * Example: board 3 6 4 1 3 4 2 5 3 0 * The goal is to reach the 0. You can move the number of spaces of your * current position in either the positive / negative direction * Solution for this game...
In Java please Consider the following problem: There are three pegs, denoted A, B, and C,...
In Java please Consider the following problem: There are three pegs, denoted A, B, and C, and N disks of different sizes. Originally, all the disks are on peg A, stacked in decreasing size from bottom to top. Your goal is to transfer all the disks to peg B, and the rules are that you can only move one disk at a time, no disk can be moved onto a smaller one, and you make use of all pegs. Develop...
JAVA: when input is type ArrayList<ArrayList<Integer>> how to use java to get this solution [ [a,b,c]...
JAVA: when input is type ArrayList<ArrayList<Integer>> how to use java to get this solution [ [a,b,c] , [d,e], [f] ] ----> [ [a,d,f], [a,e,f], [b,d,f], [b,e,f], [c,d,f], [c,e,f]] [ [a,b], [a,b,c]] ----->[[a,a],[a,b],[a,c], [b,a],[b,b],[b,c] assuming abc are integer Thanks in advance!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT