The purpose of this second MAL programming assignment is:
The "Towers of Hanoi" is a classic puzzle that can easily be solved using a recursive algorithm. The problem is stated as follows: starting with a tower of n disks of decreasing size, positioned on spindle A, move the disks, one at a time, between spindles A, B and C so that the tower of disks ends up on spindle B. You can only move a top disk and you cannot place a larger disk on top of a smaller disk. The solution to the puzzle consists of giving a sequence of moves that leads from the starting configuration to the final configuration. To see a javascript example, go to this link.
The algorithm to be used is described as follows: if there is only one disk, move it from spindle A to spindle B and you are done. This is called the base case. If there are n disks, and n > 1, then move n-1 disks from spindle A to C, using spindle B as a temporary place to put a disk, then move the largest disk from spindle A to B, then move the n-1 disks on spindle C to spindle B using spindle A as a temporary place to put a disk.
A simple C++ version of the Towers of Hanoi program follows. Your job is to write the MAL version of the program.
// If you want to run this program, save the source code in file hanoi.cc // then compile it using "%g++ hanoi.cc" and run it using "%a.out" #include <iostream.h> void Hanoi(int n, char a, char b, char c) { if (n == 1) cout << "move disk from tower " << a << " to " << b << '\n'; else { Hanoi(n-1, a, c, b); // move n-1 disks from "a" to "c" using "b" as a temporary position cout << "move disk from tower " << a << " to " << b << '\n'; Hanoi(n-1, c, b, a); // move n-1 disks from "c" to "b" using "a" as a temporary position } } int main() { int n; cout << "n? "; // use "puts prompt" in MAL cin >> n; // use "get n" in your program (really SAL) Hanoi(n, 'A', 'B', 'C'); return 0; } /* sample run follows sol13(18)% g++ hanoi.cc sol13(19)% a.out n? 3 move disk from tower A to B move disk from tower A to C move disk from tower B to C move disk from tower A to B move disk from tower C to A move disk from tower C to B move disk from tower A to B */
You must "hand in " your program via the computer by
cp p5.s ~cs354-1/handin/username/P5/.
where "p5.s" is the name of the file containing your source code and "username" is your CS login. No printouts will be turned in. I will run your program several times using different test data.