/* testfunc16.cpp CIS 150 6/9/2005 David Klick Recursive solution to Towers of Hanoi. */ #include #include using std::cin; using std::cout; int getInt(char* prompt, int min, int max); char getChoice(char* prompt, char* allowed); void moveDisks(int numDisks, int fromPole, int toPole); int main(void) { int disks; // number of disks to be moved char ans; // holds user answer for "play again?" do { // get number of disks from user (1 to 10) disks = getInt("Enter number of disks (1-10): ", 1, 10); // move all disks from first pole to third pole cout << "Moving " << disks << " disks from pole 1 to pole 3\n"; moveDisks(disks, 1, 3); // find out if user wants to play again ans = getChoice("Would you like to play again? (Y/N) ", "YyNn"); } while (ans == 'Y'); // say "Goodnight" Gracie cout << "Normal program termination.\n"; return 0; } /* Prompts user for integer, does data validation, and returns value entered. */ int getInt(char* prompt, int min, int max) { int num; do { cout << prompt; cin >> num; if (num < min) cout << "Error: value below minimum allowed\n"; else if (num > max) cout << "Error: value above maximum allowed\n"; } while (nummax); return num; } /* Prompts user for integer, does data validation, and returns the uppercase equivalent of the entered value. */ char getChoice(char* prompt, char* allowed) { char ans; do { cout << prompt; cin >> ans; ans = toupper(ans); // convert answer to upper case if (strchr(allowed, ans) == NULL) cout << "Error: Invalid choice\n"; } while (strchr(allowed, ans) == NULL); return ans; } /* This function solves the Towers of Hanoi problem by recursively moving disks from pole to pole. If there is only one disk to be moved, the routine moves it and is done. If there is more than one disk to be moved, it moves the stack of disks in pieces so that it calls this method again with fewer disks to be moved. Eventually, all calls result in moves of a single disk which can be easily solved. */ void moveDisks(int numDisks, int fromPole, int toPole) { int otherPole = 6 - fromPole - toPole; if (numDisks == 1) { cout << "Move disk from " << fromPole << " to " << toPole << '\n'; } else { moveDisks(numDisks-1, fromPole, otherPole); cout << "Move disk from " << fromPole << " to " << toPole << '\n'; moveDisks(numDisks-1, otherPole, toPole); } }