Search code examples
javaalgorithmrecursiontowers-of-hanoi

How to implement a recursive algorithm backwards


I am trying to solve a variant of the Towers of Hanoi Problem where there are three pegs but two towers of the same height and disk sizes. The task is to swap the two towers.

My solution is to stack both towers together to a big tower (disks of the same size can be stacked on top of each other) and split them up again (to switched pegs of course).

I was able to stack both towers together but I am not able to reverse my algorithm to split them up again.

In this situation there are two towers with three disks each. One on the left and one in the middle. After my algorithm there is one tower with six disks on the right peg.

My algorithm is as follows: (I'm using Java)

public void solve() {
    combineTo(3, 0, 1, 2); // parameters: (height, from, to, temp)
    splitUp(?, ?, ?, ?);
}

private void moveDisk(int from, int to){
    // here are also a few other things going on but 
    // that doesn't matter in this case
    System.out.println("from: "+from+" - to: "+to);
}

private void moveTower( int i, int from, int to, int temp) {
    if (i == 0) return;
    else{
        moveTower( i-1, from, temp, to );
        moveDisk(from, to);
        moveDisk(from, to);
        moveTower( i-1, temp, to, from );
    }
}

private void combineTo( int i, int from, int to, int temp ){
    if (i==0) return;
    else{
        combineTo(i-1, from, to, temp);
        moveDisk(to, from);
        moveTower(i-1, temp, to, from);
        moveDisk(from, temp);
        moveDisk(from, temp);
        moveTower(i-1, to, temp, from);
    }
}

private void splitUp( int i, int from, int to, int temp ){
    if (i==0) return;
    else{
        ???
    }
}

So how do I reverse this with the splitUp method?


Solution

  • As Gene said, I already had the hardest part. With the algorithm I provided in my question, I already had one big stack on the right.

    I then moved that stack with the classic hanoi algorithm to the left and added the following recursive algorithm.

    public void solve() {
        combineTo(i, 0, 1, 2); // combines 2 stacks to the right
        hanoi(2*i, 2, 0, 1); // moves big stack to the left
        splitTower(2*i, 0, 1, 2); // splits tower up again
    }
    
    private void splitTower( int i, int from, int to, int temp) {
        if (i == 0) return;
        else{
            hanoi(i-1, from, to, temp);
            splitTower( i-1, to, from, temp );
        }
    }
    
    
    private void hanoi( int i, int from, int to, int temp) {
        if (i == 0) return;
        else{
            hanoi( i-1, from, temp, to );
            moveDisk(from, to);
            hanoi( i-1, temp, to, from );
        }
    }