Question

5.37 (Towers of Hanoi: Iterative Solution) Any program that can be implemented recursovely be implemented iteratively,...

5.37 (Towers of Hanoi: Iterative Solution) Any program that can be implemented recursovely be implemented iteratively, although sometimes with considerably more difficulty and cond- ably less caricy. Try writing an iterative version of the Towers of Hanoi. If you succeed, compare Toweiterzise version with the recursive version you developed in Exercise 5.36. Investigate issues af performance, darity, and your ability to demonstrate the correctness of the programs.

java programming

Homework Answers

Answer #1

Recursive:

class Application

{

    static void towerOfHanoi(int n, char src, char dest, char aux)

    {

        if (n == 1)

        {

            System.out.println("Move disk 1 from rod " + src+ " to rod " + dest);

            return;

        }

        towerOfHanoi(n-1, src, aux, dest);

        System.out.println("Move disk " + n + " from rod " + src + " to rod " + dest);

        towerOfHanoi(n-1, aux, dest, src);

    }

public static void main(String args[])

    {

        int n = 5;

        towerOfHanoi(n, 'X', 'Y', 'Z');

    }

}

Iterative:

class Application{
static void TowerOfHanoi(src,dest, aux, numDisks){

int moves= pow(2, numDisks) - 1;

if(moves%2==0){

char temp = dest;

dest = aux;

aux = temp;

}

for(int i = 1 ;i< moves; i++){

a. if i%3 == 1: legal movement of top disk b/w source pole and destination pole.

b. if i%3 == 2: legal movement of top disk b/w source pole and auxiliary pole.

c. if i%3 == 0: legal movement of top disk b/w auxiliary pole and destination pole.

}


}
public static void main(String args[]){

        int n = 5;

        towerOfHanoi(n, 'X', 'Y', 'Z');

}

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions