/******************************************** Filename: towers.cpp Author: Grant Braught Date: 3/30/98 Modified: 3/30/98 GWB Purpose: CS132 Dickinson College Program that uses recursion to solve the towers of Hanoi problem... **********************************************/ #include // Function prototypes: void getValues(int &numDisks, char &fromPeg, char &toPeg, char &auxPeg); // Read in the number of disks, the peg from // which the disk are moved and the peg to which // they are moved. void SolveTowers(int numDisks, char fromPeg, char toPeg, char auxPeg); // Print out the steps requird to move numDisks from the // fromPeg to the toPeg using the auxPeg. int main() { int numDisks; char fromPeg; char toPeg; char auxPeg; getValues(numDisks,fromPeg,toPeg,auxPeg); // Get the values... SolveTowers(numDisks, fromPeg, toPeg, auxPeg); // Solve the puzzle. // Main always returns 0. return 0; } void SolveTowers(int numDisks, char fromPeg, char toPeg, char auxPeg) // Print out the steps requird to move numDisks from the // fromPeg to the toPeg using the auxPeg. { if (numDisks == 1) // The problem is easy! cout << "Move disk 1 from " << fromPeg << " to " << toPeg << "." << endl; else // The problem is not so easy... { // Move N-1 disks from the fromPeg to the auxPeg // using the toPeg. SolveTowers(numDisks-1, fromPeg, auxPeg, toPeg); // Move the last disk from the fromPeg to the toPeg... cout << "Move disk " << numDisks << " from " << fromPeg << " to " << toPeg << "." << endl; // Move the N-1 disks from the auxPeg to the toPeg // using the fromPeg. SolveTowers(numDisks-1, auxPeg, toPeg, fromPeg); } } void getValues(int &numDisks, char &fromPeg, char &toPeg, char &auxPeg) // Read in the number of disks, the peg from // which the disk are moved and the peg to which // they are moved. { cout << "Solve the Towers of Hanoi problem..." << endl; cout << "Enter the number of Disks: "; cin >> numDisks; cout << "Enter the peg containing the disks [a,b,c]: "; cin >> fromPeg; cout << "Enter the peg to move the disks to [a,b,c]: "; cin >> toPeg; cout << "Enter the other peg [a,b,c]: "; cin >> auxPeg; // NOTE: In reality this function should do some error checking. // It could check to make sure that the fromPeg and toPeg are // different and that they are valid. It should // only offer the 2 remaining pegs when asking for the toPeg. // It could also determine the auxPeg automatically based on // the other two. This would all improve the interface of // the program. }