0
votes

I am trying to write a recursive C function which would solve the tower of Hanoi , but with an extra restriction , that moving a disc from A (the source tower) to C (the destination tower) is forbidden , and vice versa. For instance , moving a single disc from A to C or C to A , would require using the auxiliary tower (B).

I found a normal recursive Hanoi tower code from geeksforgeeks and checked a CS page which discussed the same problem , but I cant understand the mathematical algorithm (compared to a C function)

void tower(int n, char from, char to, char aux)
{
    if (n == 1 && (from=='B' || to=='B'))
    {
        printf("\n Move 1 from %c to %c", from, to);
        return;
    }
    if(n==1) {
       printf("\n Move 1 from %c to %c", from, aux);
       printf("\n Move 1 from %c to %c", aux, to);
       return;
    }

    tower(n-1, from, aux, to);

    if( from == 'B' || to=='B' ){
        printf("\n Move %d from %c to %c", n, from, to);
    }
    else{
        printf("\n Move %d from %c to %c", n, from, aux);
    }

    tower(n-1, aux, to, from);
}

this is the function from geeksforgeeks , modified to not violate the extra restriction , but now it keeps moving larger disks on top of the smaller disks.

I am wondering how this can be fixed and whether it is possible to modify this function for that restriction or not? Thanks in advance !

edit: I am only allowed to move a single disc at a time , so some currently available algorithms cannot be implemented either.

1
You should be able to move as you please, just check if the top piece is smaller than the one you are moving, before allowing the move.Lundin
Hi, the restriction is part of the question (Im supposed to write it in a way that it would not move from source to destination)arman5592
Hi, I am not allowed to move more than a single disc at a time :(arman5592
The standard Tower of Hanoi algorithm only allows you to move a single disc at a time. I don’t understand what the additional restriction is meant to do.Jonathan Leffler

1 Answers

2
votes

thanks everyone! I found a C++ code so I'll post it down here with some modifications in case anyone has the same question later on:

void hanoi(int n,string src, string itm, string des)
{
    if (n>=1){
        hanoi((n-1),src,itm,des);
        cout<<"Move Plate "<<n<<" from "<<src <<" to "<<itm<<"\n";
        hanoi((n-1),des,itm,src);
        cout<<"Move Plate "<<n<<"from "<<itm <<" to "<<des<<"\n";
        hanoi((n-1),src,itm,des);
    }
}