1: /** @file hanoi.cpp
2: Describes the movement of discs to solve the Towers of Hanoi problem.
3: */
5: #include <iostream>
6: using namespace std;
8: #include "utilities.h"
9: using Scobey::Pause;
10: using Scobey::ReadInt;
11: using Scobey::userSaysYes;
13: void DescribeDiscMoves
14: (
15: int n, //in
16: int startPost, //in
17: int endPost //in
18: )
19: /**<
20: Display the order in which disks must be moved and to which
21: posts in order to move n disks from startPost to endPost.
22: @return Nothing.
23: @param n The number of disks to be moved.
24: @param startPost The post holding all disks at the start.
25: @param endPost The post to which all disks must be moved.
26: @post n, startPost and endPost have been initialized.
27: @post All moves necessary for moving n disks from startPost to
28: endPost have been displayed.
29: */
30: {
31: int tempPost;
32: if (n == 1)
33: cout << "Move the top disc from post "
34: << startPost << " to post " << endPost << ".\n";
35: else
36: {
37: tempPost = 6 - startPost - endPost;
38: DescribeDiscMoves(n-1, startPost, tempPost);
39: cout << "Move the top disc from post "
40: << startPost << " to post " << endPost << ".\n";
41: DescribeDiscMoves(n-1, tempPost, endPost);
42: }
43: }
45: int main()
46: {
47: cout << "\nThis program solves the Tower of Hanoi problem by "
48: "describing the sequence\nof disc moves that will achieve "
49: "the transfer of n discs from the initial\npost to the "
50: "final post, according to the following rules: \n\n"
51: "1. Only one disc can be moved at a time.\n"
52: "2. No disc can be placed on top of a smaller disc.\n\n"
53: "The amount of time to compute the moves increases "
54: "dramatically as the\nnumber of discs increases. For "
55: "illustrative purposes keep the number\nof discs to "
56: "four or five at most.\n";
57: Pause();
58: do
59: {
60: int n;
61: ReadInt("How many discs would you like to move? ", n);
62: DescribeDiscMoves(n, 1, 3);
63: cout << endl;
64: }
65: while (userSaysYes("Do it again?"));
66: }