S
Sonia
Hi,
I have written this code for the Tower of Hanoi problem. I was just
wondering if there is any way of optimizing this code ?
It's a failry simple code, but I thought that maybe somehow it could be
improved. Please let me know. Thanks
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void move(int, int, int, int);
int count = 0;
int main() {
int numToBeMoved;
int peg1=1; // peg on which the disks are initially
int peg2=2; // peg to which the disks are to be moved
int peg3=3; // temporary holding area
cout<<"Enter number of disks to be moved: ";
cin>>numToBeMoved;
move(numToBeMoved, peg1, peg2, peg3);
cout<<"Number of moves: "<<count<<endl;
return 0;
}
void move (int n, int p1, int p2, int p3)
{
if(n>=1) {
move(n-1, p1, p3, p2);
count++;
cout<<"move from "<<p1<< " to " <<p2<<endl;
move(n-1, p3,p2,p1);
}
}
I have written this code for the Tower of Hanoi problem. I was just
wondering if there is any way of optimizing this code ?
It's a failry simple code, but I thought that maybe somehow it could be
improved. Please let me know. Thanks
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void move(int, int, int, int);
int count = 0;
int main() {
int numToBeMoved;
int peg1=1; // peg on which the disks are initially
int peg2=2; // peg to which the disks are to be moved
int peg3=3; // temporary holding area
cout<<"Enter number of disks to be moved: ";
cin>>numToBeMoved;
move(numToBeMoved, peg1, peg2, peg3);
cout<<"Number of moves: "<<count<<endl;
return 0;
}
void move (int n, int p1, int p2, int p3)
{
if(n>=1) {
move(n-1, p1, p3, p2);
count++;
cout<<"move from "<<p1<< " to " <<p2<<endl;
move(n-1, p3,p2,p1);
}
}