What exactly is my teacher asking for here? Write a recursive program to impleme
ID: 3629105 • Letter: W
Question
What exactly is my teacher asking for here?Write a recursive program to implement the Tower of Hanoi. Do NOT print out the intermediate positions, since the point of this exercise is just to see how long the program takes to run.
Start with n = 10; that is, 10 disks. Keep experimenting with various values of n until you find one for which the program takes between 5 and 15 seconds. Measure approximately (by looking at your watch or a clock on the wall) how many seconds the program takes to run, for this value of n.
Now increase n by 1 and run the program again. Measure, again, how long the program takes to run.
I'm not really sure what he's asking me to do. If you could help decode this mystery, that would be awesome! Thanks!
Josiah
Explanation / Answer
please rate - thanks
you didn't specify the language.
here is C++ and Java
he wants you to run it with various values starting with 10.
and time how long it takes (just with a watch or clocks second hand) with each value
C++
#include<iostream>
using namespace std;
void hanoi(int n, int from, int to , int use);
main()
{int n;
cout<<"How many disks do you have? ";
cin>>n;
hanoi(n,1,2,3);
system("pause");
return 0;
}
void hanoi(int n, int from, int to , int use)
{
if(n==1)
return;
else
{
hanoi(n-1,from,use,to);
hanoi(1,from,to,use);
hanoi(n-1,use,to,from);
}
}
---------------------
Java
import java.util.*;
public class hanoi
{
public static void main(String[] args)
{int n;
Scanner in=new Scanner(System.in);
System.out.print("How many disks do you have? ");
n=in.nextInt();
hanoi(n,'A','B','C');
}
public static void hanoi(int n, char from, char to , char use)
{ if(n==1)
return;
else
{
hanoi(n-1,from,use,to);
hanoi(1,from,to,use);
hanoi(n-1,use,to,from);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.