Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Towers Of Hanoi Java Recursion

Tags:

java

recursion

Good evening everyone,

I have a quick question on a homework assignment my class is doing about recursion. The idea is that we have this towers of hanoi program, and we need to write a main that will make a table that will display the numbers 5-25, and how many moves it would take to solve a tower of that size, for example

5 ---- 31 Moves

6 ---- 63 Moves

etc...

I am having a little bit of trouble doing that as the TowersOfHanoi class is set up to print out each move, and I don't think we're supposed to get rid of that, but I'm not too sure.

Here is the TowersOfHanoi class

public class TowersOfHanoi {
    private int totalDisks;
    private int count;

    public TowersOfHanoi(int disks) {
        totalDisks = disks;
        count = 0;
    }

    public void solve() {
        moveTower (totalDisks,1,3,2);
    }

    private void moveTower(int numDisks, int start, int end, int temp) {
        if (numDisks ==1) {
            moveOneDisk(start,end);
        }
        else {
            moveTower (numDisks-1, start, temp, end);
            moveOneDisk (start, end);
            moveTower (numDisks-1, temp, end, start);
        }
    }

    private void moveOneDisk(int start, int end) {
        count = count+1;
        System.out.println("Move one disk from "+start+" to "+end+" - Move "+count);
    }
}

Now I just need to write a main that will create that table without printing out every single move for every single tower, but I'm not really sure how to. Any help is much appreciated

like image 260
salxander Avatar asked May 18 '26 06:05

salxander


1 Answers

You'll need one object of TowersOfHanoi class for each disk you'll be solving the puzzle for. For this you'll create these objects in the main method by passing them different arguments (from 5 to 25). Once the object is constructed you just call the solve method on it.

I'll leave the implementation to you as this is tagged homework.

like image 121
codaddict Avatar answered May 19 '26 19:05

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!