# Thread: Adding a timer to a recursive function

1. ## Adding a timer to a recursive function

Hey, I have a recursive fxn that happens to be the algorithm for the Tower of Hanoi. I need to count how many times it makes a move, but I do not know where to add the simple code of move++ or something of that nature. If you could help me that would be great. Thanks. Here is the code:

Code:
```void Move(int n, char source, char destination, char spare)
{

if (n == 1)
{
cout << "Move the top disk from " << source
<< " to " << destination << endl;

}
else
{

Move (n - 1, source, spare, destination);
Move (1, source, destination, spare);
Move (n - 1, spare, destination, source);

}
}```

2. no one has any suggestions?

3. Could you elaborate on your problem? It's not clear to me exactly what you're trying to achieve.

4. basically i need to create a counter to count how many times the fxn is called recursively. Say like this:

Code:
```int timer(int moves)//fxn to calculate # of moves
{
return moves++;
}

void Move(int n, char source, char destination, char spare,int moves)
{
timer(moves);//counts the number of times the fxn is called
if (n == 1)
{
cout << "Move the top disk from " << source
<< " to " << destination << endl;
cout << endl << moves << endl;
}

else
{

Move (n - 1, source, spare, destination,moves);
//timer(moves);//counts the number of times the fxn is called
Move (1, source, destination, spare,moves);
//timer(moves);//counts the number of times the fxn is called
Move (n - 1, spare, destination, source,moves);
//timer(moves);//counts the number of times the fxn is called

}
}```
I tried putting the timer function everywhere... didn't work. The output was wrong.

I want it to print out :
Move the top disk from A to B
number of moves 1 total
Move the top disk from B to C
number of moves 2 total
.... and so on..

5. Not for people who only wait 5 hours before bumping their threads

Besides, its not like you have a lot of choices
You put the ++moves inside the if part or the else part, and you see which one gives you the right answer.

6. I assume you have some mechanism for evaluating the final number of moves--either a cout statement in each function call if you pass the moves parameter by value as in the posted code, or a single cout statement back in the original calling function if you pass the moves parameter as a reference?

7. Try:
Code:
```void Move(int n, char source, char destination, char spare)
{
moves++;
if (n == 1)
{
cout << "Move the top disk from " << source
<< " to " << destination << endl;

}
else
{
Move (n - 1, source, spare, destination);
Move (1, source, destination, spare);
Move (n - 1, spare, destination, source);

}
}```

8. Make a global var and increment it each time the function is gone through..basically.

Popular pages Recent additions