Pages

Wednesday, January 11, 2012

TOWER OF HONAI



TOWER OF HONAI NON-RECURSIVE PROGRAM  IN "C"

void main()

{
      int n,i,j,moves,dsk=0,a;
     // n represents the no.of disks(i.e.the height of the tower),i and j are used for iteration purpose
    //  moves represent the no.of moves required for a tower of height n
   //  dsk used to indicate the disk to be moved
     int from,to;
     char ch[3]={'A','B','C'};
     printf("Enter the no.of disks.....");
     scanf("%d",&n);
     moves=1<<n;
     for(i=1;i<moves;i++)
    {
       //logic to determine the disk to move
        for(a=i,dsk=0;a%2==0;a=a>>1,dsk++);
        dsk++;
      //logic to determine the pegs
      from=(i&i-1)%3;
      to=((i|i-1)+1)%3;
    //print the statement
    printf("Move disk %d from %c to %c\n",dsk,ch[from],ch[to]);
    }
   getch();
}



TOWER OF HONAI RECURSIVE PROGRAM  IN "C"


#include<stdio.h>
#include<conio.h>
void rec(char[],int);
void main()
{

    int n,moves;
    char ch[3]={'A','B','C'};
    clrscr();
    printf("Enter the no.of disks.....");
    scanf("%d",&n);
    moves=1<<n;
    printf("\nRecur:\n");
    rec(ch,moves-1);
    getch();
}

void rec(char ar[],int i)
{
  int dsk=0,a;
  for(a=i;a%2==0;a/=2,dsk++);
  dsk++;
  if(i==1)
  {
    printf("Move disk %d from %c to %c\n",dsk,ar[(i&i-1)%3],ar[((i|i-1)+1)%3]);
    return;
  }
  else
  {
    rec(ar,i-1);
    printf("Move disk %d from %c to %c\n",dsk,ar[(i&i-1)%3],ar[((i|i-1)+1)%3]);
  }
}





No comments:

Post a Comment