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

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
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