Computer Science 2611
Summer 2000
Programming Assignment 5

Handed out: June 29.

A puzzle

The Towers of Hanoi puzzle has three posts and some number n of disks. Each disk has a hole in the middle, so that it can be put on a post, and the disks are of different sizes.

Initially, the disks are all stacked on the leftmost post, with larger disks closer to the bottom and smaller disks closer to the top. For example, if there are three disks, the puzzle starts out looking like this.

The object is move all of the disks from the leftmost post to the rightmost post. So when the puzzle is solved, it looks like this.

But there are some rules that must be followed.

  1. Only one disk can be held at a time.

  2. A disk can only be put down by placing it on one of the posts. For example, you can't put a disk on the table beside the puzzle.

  3. No disk can ever be put on top of a smaller disk.

The assignment

Write a program that prints instructions for solving the Towers of Hanoi puzzle. It should read a number of disks from the user and print the solution. The posts should be called L (for left), M (for middle) and R (for right).

Number the moves, starting at move 1. For example, if the number of disks is 3, then the following would be printed.

  1. Move a disk from post L to post R.
  2. Move a disk from post L to post M.
  3. Move a disk from post R to post M.
  4. Move a disk from post L to post R.
  5. Move a disk from post M to post L.
  6. Move a disk from post M to post R.
  7. Move a disk from post L to post R.
The disk to be moved is always the top one on the post.

Hints

Use recursion. Write a function that takes four parameters: the number of disks to move, the name of the post that contains those disks, the name of the destination post to which they should be moved and the name of the other post (the one that is neither the source nor the destination). Use type char for the name of the posts.

It is easy to move no disks. To move n disks from post A to post B, using post C as the other post, first ask a friend to move n-1 disks from post A to post C. Then move the largest disk from post A to post B. Finally, ask a friend to move n-1 disks from post C to post B.

Test your solution, and check whether the instructions that it prints work. When it is working, print it and turn it in.