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.
Students must send the code and outputs

Solutions

Expert Solution

Greetings!!!!!!!!!!

Please find below the Iterative approach (program) to Tower of Hanoi with screen shot of sample run. It is for 4 disks and 3 bars.



public class Main
{
    
     // A structure is defined to indicate a stack
    class intermediateStack
    {
        int size;
        int top;
        int array[];
    }

    // Function to create a stack of given maximum capacity.
    intermediateStack createStack(int max)
    {
        intermediateStack stack = new intermediateStack();
        stack.size = max;
        stack.top = -1;
        stack.array = new int[max];
        return stack;
    }

    // Stack is full when the top is equal to the size - 1 (last index)
    boolean isFull(intermediateStack stack)
    {
        return (stack.top == stack.size - 1);
    }

    // Stack is empty when top is equal to -1
    boolean isEmpty(intermediateStack stack)
    {
        return (stack.top == -1);
    }

    // Function to push an item into the stack. 
    // It also increases value of top by 1
    void push(intermediateStack stack, int valItem)
    {
        if (isFull(stack))
                return;
                
        stack.array[++stack.top] = valItem;
    }

    // Function to pop an item from the stack.
    // it also decreases top by 1
    int pop(intermediateStack stack)
    {
        if (isEmpty(stack))
                return Integer.MIN_VALUE;
                
        return stack.array[stack.top--];
    }

    // Function to implement legal movement between two bars
    void moveDisksBetweenTwoBars(intermediateStack src, intermediateStack dest, String source, String destination) 
    {
        int bar1TopDisk = pop(src);
        int bar2TopDisk = pop(dest);
    
        // When bar 1 is empty
        if (bar1TopDisk == Integer.MIN_VALUE) 
        {
                push(src, bar2TopDisk);
                moveDisk(destination, source, bar2TopDisk);
        }
        
        // When bar 2 is empty
        else if (bar2TopDisk == Integer.MIN_VALUE) 
        {
                push(dest, bar1TopDisk);
                moveDisk(source, destination, bar1TopDisk);
        }
        
        // When top disk of bar 1 > top disk of bar 2
        else if (bar1TopDisk > bar2TopDisk) 
        {
                push(src, bar1TopDisk);
                push(src, bar2TopDisk);
                moveDisk(destination, source, bar2TopDisk);
        }
        // When top disk of bar 1 < top disk of bar 2.
        else
        {
                push(dest, bar2TopDisk);
                push(dest, bar1TopDisk);
                moveDisk(source, destination, bar1TopDisk);
        }
    }

    // Function to show the movement of disks between bars
    void moveDisk(String from, String to, int disk)
    {
        System.out.println("Move the disk " + disk + 
                                                        " from " + from + 
                                                        " to " + to);
    }

    // Function to implement Tower Of Hanoai problem.
    void iterativeTOH(int number_of_disks, intermediateStack src, intermediateStack aux, intermediateStack dest)
    {
        int x, total_number_of_moves;
        String s = "Source Bar";
        String d = "Destination Bar";
        String a = "Auxiliary Bar";
    
        // If number of disks is even, then 
        // interchange destination bar and auxiliary bar
        if (number_of_disks % 2 == 0)
        {
                String temp = d;
                d = a;
                a = temp;
        }
        total_number_of_moves = (int)(Math.pow(2, number_of_disks) - 1);
    
        // Larger disks will be pushed first
        for(x = number_of_disks; x >= 1; x--)
                push(src, x);
    
        for(x = 1; x <= total_number_of_moves; x++)
        {
                if (x % 3 == 1)
                moveDisksBetweenTwoBars(src, dest, s, d);
    
                else if (x % 3 == 2)
                moveDisksBetweenTwoBars(src, aux, s, a);
    
                else if (x % 3 == 0)
                moveDisksBetweenTwoBars(aux, dest, a, d);
        }
    }  


    public static void main(String[] args)
    {
        
        // Input: number of disks is given as 4.
        int number_of_disks = 4;
        
        Main ob = new Main();
        intermediateStack source, destination, auxiliary;
        
        // Create three stacks of size 'number_of_disks' (4 in our case)
        // to hold the disks
        source = ob.createStack(number_of_disks);
        destination = ob.createStack(number_of_disks);
        auxiliary = ob.createStack(number_of_disks);
        
        ob.iterativeTOH(number_of_disks, source, auxiliary, destination);
    }
}

Please find below the Recursive approach (program) to Tower of Hanoi with screen shot of sample run. It is for 4 disks and 3 bars.


public class Main
{
    
    // Java recursive function to solve tower of hanoi problem 
    static void TOH(int Number_of_disks, String from_bar, String to_bar, String aux_bar) 
    { 
        if (Number_of_disks == 1) 
        { 
            System.out.println("Move the disk 1 from " +  from_bar + " Bar to " + to_bar + " Bar"); 
            return; 
        } 
        TOH(Number_of_disks-1, from_bar, aux_bar, to_bar); 
        System.out.println("Move the disk " + Number_of_disks + " from " +  from_bar + " Bar to " + to_bar + " Bar"); 
        TOH(Number_of_disks-1, aux_bar, to_bar, from_bar); 
    } 
      
   
    public static void main(String args[]) 
    { 
        //Input: Number of Disks is given as 4.
        int n = 4; 
        
        // Source, Auxiliary, and Destination are names of bars.
        TOH(n, "Source", "Destination", "Auxiliary");  
    } 
}

Thank You


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
There is a famous puzzle called the Tower of Hanoi. Code the recursive implementation of it...
There is a famous puzzle called the Tower of Hanoi. Code the recursive implementation of it with Python.
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...
I have a recursive Tower of Hanoi program and would like to get the index numbers...
I have a recursive Tower of Hanoi program and would like to get the index numbers to be in correct sequence: 1,2,3,4,5,6,7. How can I do this? Main.java import java.io.*; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args){ /**There is a stack of N disks on the first of three poles (call them A, B and C) and your job is to move the disks from pole A to pole C without ever putting a...
My recursive Tower of Hanoi program does not render the correct index numbers. Also, it does...
My recursive Tower of Hanoi program does not render the correct index numbers. Also, it does not prompt user to enter the starting rod letter and the ending rod letter. Could you help me fix it? Main.java import java.io.*; import java.util.List; import java.util.Scanner; public class Main { int index = 1; public static void main(String[] args) { /**There is a stack of N disks on the first of three poles (call them A, B and C) and your job is...
i want it in C++.You will solve the Towers of Hanoi problem in an iterative manner...
i want it in C++.You will solve the Towers of Hanoi problem in an iterative manner (using Stack) in C++(using data structure). Note: you have to solve for N number of disks, 3 Towers (Stacks). Do not use recursion. For better understanding play the game at least once. Link:https://www.mathsisfun.com/games/towerofhanoi.html
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...
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...
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 =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT