So here I have a program that shows the simulation of solving the Hanoi puzzle.
ID: 3865824 • Letter: S
Question
So here I have a program that shows the simulation of solving the Hanoi puzzle. My program works fine for the most part but does not terminate when it should. It should terminate once all discs are on the C peg (C C C), but mine continues to a fourth disc which is not given. There should only be three discs. Any help would be appreciated!
//////////////////////////////////////////////////////////////////////////////////////
#include
using namespace std;
const int num = 3;
const char from_peg = 'A';
const char to_peg = 'B';
const char temp_peg = 'C';
char position[num];
void moveDiscs(int num,int disc,char source,char dest, char spare){
if (disc == 0){
position[disc]=dest;
cout<<"Moved disc "<
cout<<" ( ";
for(int i = 0;i
cout<
}
cout<<")"<
}else{
moveDiscs(num,disc-1,source,spare,dest);
position[disc]=dest;
cout<<"Moved disc "<
cout<<" ( ";
for(int i = 0;i
cout<
}
cout<<")"<
moveDiscs(num,disc-1,spare,dest,source);
}
}
int main() {
cout<<"Starting Position for 3 discs are (";
for(int i = 0;i
position[i]='A';
cout<
}
cout<<")"<
moveDiscs(3,3,from_peg,to_peg,temp_peg);
return 0;
}
/////////////////////////////////////////////////////////////////////////
output:
Starting Position for 3 discs are (A A A )
Moved disc 1 to peg C ( C A A )
Moved disc 2 to peg B ( C B A )
Moved disc 1 to peg B ( B B A )
Moved disc 3 to peg C ( B B C )
Moved disc 1 to peg A ( A B C )
Moved disc 2 to peg C ( A C C )
Moved disc 1 to peg C ( C C C ) <--- I need it to stop here
Moved disc 4 to peg B ( C C C )
Moved disc 1 to peg B ( B C C )
Moved disc 2 to peg A ( B A C )
Moved disc 1 to peg A ( A A C )
Moved disc 3 to peg B ( A A B )
Moved disc 1 to peg C ( C A B )
Moved disc 2 to peg B ( C B B )
Moved disc 1 to peg B ( B B B )
Explanation / Answer
#include<stdio.h>
main()
{
int n;
scanf("%d",&n);
printf("A-->Source B-->Destination C-->Auxliary ");
toh(n,'A','B','C');
}
void toh(int n,char X,char Y,char Z)
{
static int i=1;
if(n==0)
return;
if(n==1)
{
printf(" %d) %c to %c",i++,X,Y);
}
else
{
toh(n-1,X,Z,Y);
printf(" %d) %c to %c ",i++,X,Y);
toh(n-1,Z,Y,X);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.