Temple of Hanoi

Hello, so I have this temple of Hanoi program which works fine, I just don't know how to code in a count to keep track of steps taken. I tried starting a count each move and returning the value but I returns the wrong amount. Its probably something simple it always is, but if you can fix before I figure it out I would appreciate it. Thanks for your time.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  #include <iostream>

using namespace std;

int towerHanoi(int disks, char a, char b, char c);

int main()
{
    int disks, count;
    char a, b , c;
    cout <<"Welcome to The Tower of Hanoi!!! " << endl;
    cout <<" " << endl;
    cout <<"How many disks? " << endl;
    cin >> disks;
    
    towerHanoi(disks, 'A', 'B', 'C');
    
    cout <<" Number of turns: " << count << endl;
    
    system("pause");
    
    return 0;
}
int towerHanoi(int disks, char a, char b, char c)
{
    int count = 0; 
    if(disks == 0)
    {
             cout <<"Move disk from :" <<a<< " to " <<b << endl;
             count = count +1; 
             }
     else
     {
         towerHanoi(disks - 1, a, c, b);
         count = count +1; 
         cout <<"Move disk from :" <<a<< " to " <<b << endl;
         towerHanoi(disks - 1, c, b, a);
         count = count +1; 
         }
        return count; 
         
}                  
Last edited on
34
35
towerHanoi(disks - 1, a, c, b);
count = count +1; 

Certainly, it does not take only one move to move disks - 1 disks from A to C, right?

But you know that towerHanoi(disks - 1, a, c, b) returns the number of moves it took to move those disks - 1 disks.
So you should be adding that value to count.

Same with your other recursive call to towerHanoi.
So i should just return my general case and output that rather then try and do a increment count ?
I meant to try changing
34
35
towerHanoi(disks - 1, a, c, b);
count = count +1;
to just
34
35
count += towerHanoi(disks - 1, a, c, b);
// and similarly for your other one 
.
Ok ill try that. Thanks
Hey so i tried that, but it kept outputting the wrong number of steps. Maybe im just doing it wrong?
Topic archived. No new replies allowed.