In: Computer Science
**C++ only, standard library.
We are supposed to create a tower of hanoi program and do a sequence of 100 disks. We are supposed to run the program and then answer two questions:
1) How long does your computer take to run(time)?
2) If I could move 1 disk per second how long would it take?
Here is my program so far:
void towerOfHanoi(int numDisks, char from_rod, char to_rod, char
aux_rod)
{
int count=0;
if (numDisks == 1)
{
//cout << "Move disk 1 from rod " << from_rod
<<
// " to rod " << to_rod<<endl;
return;
}
towerOfHanoi(numDisks - 1, from_rod, aux_rod, to_rod);
//cout << "Move disk " << numDisks << " from
rod " << from_rod <<
//" to rod " << to_rod << endl;
towerOfHanoi(numDisks - 1, aux_rod, to_rod, from_rod);
}
// Driver code
int main()
{
int numDisks; // Number of disks
cout<<"This program solves the Hanoi Tower
puzzle"<<endl<<endl;
cout<<"Enter the number of disks to calculate: ";
cin>>numDisks;
towerOfHanoi(numDisks, 'A', 'C', 'B'); // A, B and C are names of
rods
return 0;
}
#include <iostream>
#include <algorithm>
#include <chrono>
using namespace std;
using namespace std::chrono;
int moves = 0;
void towerOfHanoi(int numDisks, char from_rod, char to_rod, char
aux_rod)
{
moves++;
int count=0;
if (numDisks == 1)
{
//cout <<
"Move disk 1 from rod " << from_rod <<
// " to rod "
<< to_rod<<endl;
return;
}
towerOfHanoi(numDisks - 1, from_rod,
aux_rod, to_rod);
//cout << "Move disk " <<
numDisks << " from rod " << from_rod <<
//" to rod " << to_rod <<
endl;
towerOfHanoi(numDisks - 1, aux_rod, to_rod,
from_rod);
}
// Driver code
int main()
{
int numDisks; // Number of disks
cout<<"This program solves the Hanoi
Tower puzzle"<<endl<<endl;
cout<<"Enter the number of disks to
calculate: ";
cin>>numDisks;
// Get starting timepoint
auto start =
high_resolution_clock::now();
towerOfHanoi(numDisks, 'A', 'C', 'B'); //
A, B and C are names of rods
auto stop =
high_resolution_clock::now();
auto duration =
duration_cast<microseconds>(stop - start);
cout << "Time taken: "
<<
duration.count() << " microseconds" << endl;
cout << "Number of disk movements: "
<< moves << endl;
return 0;
}
**************************************************
The above code can be used to measure the time taken in reality..
And also it shows how many disk movements happen.
If you notice below, for n = 10, We get (2^n - 1) movements.
Similarly, For n = 3,
Hence, For n = 100 disks, (2^100 - 1) movements will be required, which is 1267650600228229401496703205375 movements.
Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.