Search code examples
ctowers-of-hanoi

Tower of Hanoi (Frame Stewart) k pegs in c


Is there any implimentation of Frame Stewart algorithm in C language. I have the following code in python which works fine.

def FrameStewart(ndisks,npegs):
    if ndisks ==0: #zero disks require zero moves
        return 0
    if  ndisks == 1 and npegs > 1: #if there is only 1 disk it will only take one move
        return 1
    if npegs == 3:#3 pegs is well defined optimal solution of 2^n-1
        return 2**ndisks - 1
    if npegs >= 3 and ndisks > 0:
        potential_solutions = (2*FrameStewart(kdisks,npegs) + FrameStewart(ndisks-kdisks,npegs-1) for kdisks in range(1,ndisks))
        return min(potential_solutions) #the best solution
    #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk)
    return float("inf") 

a = int(raw_input("Disks [>] "))
b = int(raw_input("rods [>] "))
print FrameStewart(a, b) #prints 161 

I wrote the following C code but it's not giving correct output

#include<stdio.h>

int power(int a, int b){
    int p=1,i;
    for(i=0;i<b;i++){
        p*=a;
    }
    return p;
}

int min(int abc[],int n){
    int min = abc[0],i;
    for(i=1;i<n;i++)
    {
        if(abc[i]<min){
            min = abc[i];
        }
    }
    return min;
}

int hanoi(int rods, int disks)
{
    int moves=2147483647,i;
    if(disks==0)
        return 0;
    if(disks==1)
        return 1;
    if(rods==3)
        return power(2,disks)-1;
    if(rods>=3 && disks>0){
        int potential_moves[disks-1];
        for(i=1;i<disks;i++){
            potential_moves[i-1]=2*hanoi(i,rods) + hanoi(disks-i,rods-1);
        }
        return min(potential_moves, disks-1);
    }
    return moves;
}

int main(){
    int rods,disks;
    printf("***** Tower of Hanoi (for n rods) *****\n");
    printf("Enter no. of disks : ");
    scanf("%d",&disks);
    printf("Enter no. of rods : ");
    scanf("%d",&rods);
    if(disks>1 && rods<3){
        printf("Invalid input rods must be greater than 2 for 2 or more disks\n");
        return -1;
    }
    int moves = hanoi(rods, disks);
    printf("Minimum np. of moves are : %d\n", moves);
    return 0;
}

Can anyone tell me why is my code incorrect or a correct implimentation of Frame Stewart algorithm in C.


Solution

  • Your logic is correct but it have a simple yet hard-to-find mistake. You have reversed the arguments when calling the function recursively. take a look here

    potential_moves[i-1]=2*hanoi(i,rods) + hanoi(disks-i,rods-1);
    

    the line should be

    potential_moves[i-1]=2*hanoi(rods,i) + hanoi(rods-1, disks-i);
    

    and problem solved!.