So I want to count how many time the function moveSingleDisk() is called, but I can’t seem to figure it out… Using this code:
#include <iostream>
using namespace std;
void moveTower(int n, char start, char finish, char temp, int count);
void moveSingleDisk(char moveFrom, char moveTo, int count);
void calcHanoi(int n);
int main (int argc, const char * argv[])
{
calcHanoi(5);
return 0;
}
void calcHanoi(int n)
{
int count = 0;
moveTower(n, 'A', 'B', 'C', count);
}
void moveTower(int n, char start, char finish, char temp, int count)
{
if (n == 1)
{
count++;
moveSingleDisk(start, finish, count);
return;
}
moveTower(n-1, start, temp, finish, count);
count++;
moveSingleDisk(start, finish, count);
moveTower(n-1, temp, finish, start, count);
}
void moveSingleDisk(char moveFrom, char moveTo, int count)
{
cout << count << ": " << moveFrom << " -> " << moveTo << endl;
}
I get the following output:
1: A -> B
1: A -> C
2: B -> C
1: A -> B
2: C -> A
2: C -> B
3: A -> B
1: A -> C
2: B -> C
2: B -> A
3: C -> A
2: B -> C
3: A -> B
3: A -> C
4: B -> C
1: A -> B
2: C -> A
2: C -> B
3: A -> B
2: C -> A
3: B -> C
3: B -> A
4: C -> A
2: C -> B
3: A -> B
3: A -> C
4: B -> C
3: A -> B
4: C -> A
4: C -> B
5: A -> B
I’ve tried to trace the problem, but recursion makes tracing this type of thing quite difficult (at least for me).
Any help or explanation would be greatly appreciated! Thank you 🙂
You’re passing
countby value, so the recursive calls tomoveTowerdon’t modify the local copy of it. Pass by reference instead:It might be slightly neater to increment the counter inside
moveSingleDisk, rather than before each call to it, so you can be sure that you don’t miss any calls. In that case, you’ll need to pass by reference there too.