Friday, November 21, 2008

tower of hanoi recursive

#include
#include
using namespace std;
char left[20],right[20],middle[20];
void Hanoi(int n,char from[20],char to[20],char by[20]);
void print(char temp[20]) //this is to print the towers as given in the parameter
{
int size=strlen(temp);
int i=size-1;
while(i>=0) //since in this program i am storing the least value at the zeroth index it is good if the printing takes place in the reverse oreder as in the output
{
cout< i--;
}
cout<<"\n";


}
int main()
{

int n;
strcpy(::right,"\0");
strcpy(::middle,"\0");
cout<<"Enter the no of discs in the tower of hanoi (should be less than 10)\n";
cin>>n;
if (n>=10)
{
cout<<"Quiting\n";
return 0;
}
char init='1';
int i=0;
while(i {
::left[i]=init;
init++;
i++;
}
::left[i]='\0';
cout<<"Tower1: ";
print(::::left); //printing the initial state of all the towers
cout<<"Tower2: ";
print(::middle);
cout<<"Tower3: ";
print(::right);
cout<<"\n\n\n\n";
sleep(1);
Hanoi(n,::left,::right,::middle);
return 0;
}
void Hanoi(int n,char from[20],char to[20],char by[20])
{
if (n==1)
{

int size;
size=strlen(to);
int i=size+1;


while (i>0) //this is to make ready the insertion point for the element that has to be added
{
to[i]=to[i-1];
i--;
}
to[0]=from[0]; //the top most element of from will be added to the top position of to
size=strlen(from);
while(i {
from[i]=from[i+1];
i++;
}
cout<<"Tower1: ";
print(::left); //printing the present condition of all the towers
cout<<"Tower2: ";
print(::middle);
cout<<"Tower3: ";
print(::right);
cout<<"\n\n\n\n";
sleep(1);
}

else
{
Hanoi(n-1,from,by,to); //here, these are the recursive calls to the function Hanoi
Hanoi(1,from,to,by);
Hanoi(n-1,by,to,from);
}

}

1 comment:

Antony K said...

hey man chk out my blog

http://phase-shifter.blogspot.com/