In: Computer Science
Implement an iterator that produces the moves for the Towers of Hanoi puzzle described in Worked Example 11.2. Provide functions has_more_moves and next_move. The next_move function should yield a string describing the next move. For example, the following code prints all moves needed to move five disks from peg 1 to peg 3:
DiskMover mover(5, 1, 3);
while (mover.has_more_moves())
{
cout << mover.next_move() << endl;
}
Hint: A disk mover that moves a single disk from one peg to another simply has a next_move function that returns a string
Move disk from peg source to target
A disk mover with more than one disk to move must work harder. It needs another DiskMover to help it move the first d – 1 disks. Then next_move asks that disk mover for its next move until it is done. Then the next_move function issues a command to move the dth disk. Finally, it constructs another disk mover that generates the remaining moves.
It helps to keep track of the state of the disk mover:
•BEFORE_LARGEST: A helper mover moves the smaller pile to the other peg.
•LARGEST: Move the largest disk from the source to the destination.
•AFTER_LARGEST: The helper mover moves the smaller pile from the other peg to the target.
•DONE: All moves are done.
HELLO ADDING CODE IN C++ FOR YOUR REQUIREMENT
PLEASE GO THROUGH IT ONCE
THANK YOU
#include <bits/stdc++.h>
#include <string>
using namespace std;
string mover(int n,int from_rod,int to_rod)
{
return "Move disk " + std::to_string(n) + " from rod " + std::to_string(from_rod) + " to rod " + std::to_string(to_rod);
}
void towerOfHanoi(int n, int from_rod,int to_rod,int aux_rod)
{
if (n == 1)
{
cout << "Move disk 1 from rod " << from_rod <<
" to rod " << to_rod<<endl;
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << mover(n,from_rod,to_rod)<<endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}
// Driver code
int main()
{
int n = 5; // Number of disks
towerOfHanoi(n, 1, 3, 2); // 1, 3 and 2 are names of rods
return 0;
}
OUTPUT