Purpose
The goal is to move all of the disk from one tower to another tower, with the following rules:
- Move one disk at a time
- Only move from the top of the tower to the top of another tower
- Never place a larger disk on a smaller disk
Data Representation
Use an array of integer vectors, each vector is representing one of the towers, and the last element in the vector is the top of the tower.
The numbers in the vectors represent the disks. The larger the number the larger the disk. The number on the bottom of the vector or tower is NOT representing any disks; that number is there as a padding so when we call the back function on an “empty” tower it will not crash the program.
This program will use 4 variables:
- n: the number of disks to move
- from: the tower from which the disk is going to be moved from (initialize to 0)
- to: the destination tower of the disk being moved (initialize to 1 for odd n or 2 for even n)
- candidate: the number of the disc being moved (initialize to 1)
Algorithm
Move the disk on the top of the from tower to the top of the to tower
Calculate the new "from", "to", and "candidate" for the next move:
from
Compare the disk from the top of the two towers that is not the "to" tower using (to+1)%3 or (to+2)%3. These two disks are the disks that have not just been moved. Check which one is smaller and the tower with the smaller disk is the new "from" tower.
candidate
The disc on top of the "from" tower
to
The new "to" tower is the closest tower on which the candidate can be placed. If the number of disks is odd, the closest tower is (from+1)%3. Or (from+2)%3 (left) if the number of disks is even
Rinse and Repeat until the second tower or t[1] contains all of the disks
Resource
TemplateOutput
This is to be submitted on blackboard as a .cpp file. File name follows the following format: lastName_firstName.cpp