Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The Tower of Hanoi (also called the Tower of Brahma or Lucas\' Tower) is a mathe

ID: 3724588 • Letter: T

Question

The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

Only one disk can be moved at a time.

Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack.

No disk may be placed on top of a smaller disk.

With 3 disks, the puzzle can be solved in 7 moves.

Implement towerOfHanoi function that produces steps of moving disks from rod 'A' to rod 'C' using an auxiliary rod 'B'.

For example: assume tower 'A' consists of 3 disks (tower 'B' and 'C' are initially empty) and we want to move disks to tower 'C'. following instructions should be produced by towerOfHanoi function.

====================== main.cpp ===========================

#include <iostream>
using namespace std;

int main()
{
int n; // Number of disks
cout << "Enter num of disks:" << endl;
cin >> n;
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

Explanation / Answer

#include <iostream>
using namespace std;
void towerOfHanoi(int n, char from, char to, char aux);
int main()
{
int n; // Number of disks
cout << "Enter num of disks:" << endl;
cin >> n;
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

void towerOfHanoi(int n, char from, char to, char aux)
{

// base condition for the recursion
if (n == 1)
{
printf(" Disk 1 moved from %c to %c", from, to);
return;
}
towerOfHanoi(n-1, from, aux, to);
printf(" Disk %d moved from %c to %c", n, from, to);
towerOfHanoi(n-1, aux, to, from);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote