Question

In: Computer Science

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

Solutions

Expert Solution

Code recursive:

class Main 
{ 
    // recursive method 
    static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 
    { 
        if (n == 1) 
        { 
            System.out.println("Move disk 1 from rod " +  from_rod + " to rod " + to_rod); 
            return; 
        } 
        towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 
        System.out.println("Move disk " + n + " from rod " +  from_rod + " to rod " + to_rod); 
        towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 
    } 
      
    //  Driver method 
    public static void main(String args[]) 
    { 
        int n = 4; // Number of disks 
        towerOfHanoi(n, 'A', 'C', 'B');  // A, B and C are names of rods 
    } 
} 




code screenshot:

output recursive:

Code iterative:

class Main{
     
    // stack representation
    class Stack
    {
        int capacity;
        int top;
        int array[];
    }
     
    // Function to create a stack of given capacity.
    Stack createStack(int capacity)
    {
        Stack stack = new Stack();
        stack.capacity = capacity;
        stack.top = -1;
        stack.array = new int[capacity];
        return stack;
    }
     
    //checking if stack is full
    boolean isFull(Stack stack)
    {
        return (stack.top == stack.capacity - 1);
    }
     
    //checking if stack is empty
    boolean isEmpty(Stack stack)
    {
        return (stack.top == -1);
    }
     
    //adding item to the stack
    void push(Stack stack, int item)
    {
        if (isFull(stack))
            return;
             
        stack.array[++stack.top] = item;
    }
     
    // Function to remove an item from stack.It decreases top by 1
    int pop(Stack stack)
    {
        if (isEmpty(stack))
            return Integer.MIN_VALUE;
             
        return stack.array[stack.top--];
    }
     
    // function to implement legal movement between two poles
    void moveDisksBetweenTwoPoles(Stack src, Stack dest, 
                                  char s, char d) 
    {
        int pole1TopDisk = pop(src);
        int pole2TopDisk = pop(dest);
     
        // When pole 1 is empty
        if (pole1TopDisk == Integer.MIN_VALUE) 
        {
            push(src, pole2TopDisk);
            moveDisk(d, s, pole2TopDisk);
        }
         
        // When pole2 pole is empty
        else if (pole2TopDisk == Integer.MIN_VALUE) 
        {
            push(dest, pole1TopDisk);
            moveDisk(s, d, pole1TopDisk);
        }
         
        // When top disk of pole1 > top disk of pole2
        else if (pole1TopDisk > pole2TopDisk) 
        {
            push(src, pole1TopDisk);
            push(src, pole2TopDisk);
            moveDisk(d, s, pole2TopDisk);
        }
        // When top disk of pole1 < top disk of pole2
        else
        {
            push(dest, pole2TopDisk);
            push(dest, pole1TopDisk);
            moveDisk(s, d, pole1TopDisk);
        }
    }
     
    // Function to show the movement of disks
    void moveDisk(char fromPeg, char toPeg, int disk)
    {
        System.out.println("Move the disk " + disk + 
                                " from " + fromPeg + 
                                  " to " + toPeg);
    }
     
    // Function to implement TOH puzzle
    void tohIterative(int num_of_disks, Stack
                      src, Stack aux, Stack dest)
    {
        int i, total_num_of_moves;
        char s = 'A', d = 'B', a = 'C';
      
        // If number of disks is even, then 
        // interchange destination pole and
        // auxiliary pole
        if (num_of_disks % 2 == 0)
        {
            char temp = d;
            d = a;
            a  = temp;
        }
        total_num_of_moves = (int)(Math.pow(
                             2, num_of_disks) - 1);
      
        // Larger disks will be pushed first
        for(i = num_of_disks; i >= 1; i--)
            push(src, i);
      
        for(i = 1; i <= total_num_of_moves; i++)
        {
            if (i % 3 == 1)
              moveDisksBetweenTwoPoles(src, dest, s, d);
      
            else if (i % 3 == 2)
              moveDisksBetweenTwoPoles(src, aux, s, a);
      
            else if (i % 3 == 0)
              moveDisksBetweenTwoPoles(aux, dest, a, d);
        }
    }
     
    // Driver code
    public static void main(String[] args)
    {
         
        // Input: number of disks
        int num_of_disks = 4;
         
        Main m = new Main();
        Stack src, dest, aux;
         
        // Create three stacks of size 'num_of_disks'
        // to hold the disks
        src = m.createStack(num_of_disks);
        dest = m.createStack(num_of_disks);
        aux = m.createStack(num_of_disks);
         
        m.tohIterative(num_of_disks, src, aux, dest);
    }
    }

output iterative:

code screenshot iterative:


Related Solutions

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...
Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort I need it in Java with...
Iterative Linear Search, Recursive Binary Search, and Recursive Selection Sort I need it in Java with comments and I need the input file to be placed with Scanner not BufferedReader Please help I need Class River Class CTRiver and Class Driver Class River describes river’s name and its length in miles. It provides accessor methods (getters) for both variables, toString() method that returns String representation of the river, and method isLong() that returns true if river is above 30 miles...
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...
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...
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 =...
In Lecture 5, we discussed how to solve the Tower of Hanoi problem (Exercise 5.36 in...
In Lecture 5, we discussed how to solve the Tower of Hanoi problem (Exercise 5.36 in the textbook). Consider the following problem variant in which one extra constraint has been added: There are three pegs and n disks of different sizes. Initially, all disks are on the leftmost peg and arranged in order of decreasing size, with the smallest disk on top. The task is to move all the disks to the rightmost peg, under the constraints that: • Only...
design two algorithms, an iterative version and a recursive version , for finding the min and...
design two algorithms, an iterative version and a recursive version , for finding the min and max values in an array of n numbers A.) a iterative version B.) a recursive version derive the time efficiency functions (or time function in terms of n) for each, analyze each function, and compare and discuss the results of the analysis
Write a java program to solve Towers of Hanoi with the condition that there are "m"...
Write a java program to solve Towers of Hanoi with the condition that there are "m" number of rods and "n" number of disks. Where m >= 3 and n >=1.
Write a MIPS assembly language procedure that implements the Towers of Hanoi recursive function given the...
Write a MIPS assembly language procedure that implements the Towers of Hanoi recursive function given the following declaration: void towers(int n, char source, char dest, char spare); The function outputs a message describing each move. The source, destination, and spare poles are indicated with a character identifier of your choosing ('A', 'B', 'C' are common). Write a MIPS assembly language program that demonstrates the Towers of Hanoi procedure. Your program should ask the user for the number of disks. The...
DESCRIPTION Objectives To develop a recursive solution to an open-ended iterative problem To develop a program...
DESCRIPTION Objectives To develop a recursive solution to an open-ended iterative problem To develop a program that manages bad input Description Write a program (printSquares.scala) that read non-negative Int values from a user one at a time. For each positive Int, print out a message with the square of the number. Your program should quit when the use enters a negative Int. Note: You will also need to manage bad input! If the user types something in that isn't an...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT