Search code examples
c++recursiontowers-of-hanoi

In recursive Hanoi Tower how can I keep the three arrays (pillars) in order?


I wrote a Hanoi Tower program, but the output switches the A, B and C pillars because of the recursion. Is there a way to keep the pillars in order to make an animation? My code :

#include <iostream>
#include <vector>
#include <stdlib.h> 
#include <windows.h> 
using namespace std;

void printTowers(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3)
{
    printOut(arr1); //prints vector using iterator
    printOut(arr2);
    printOut(arr3);
}
//------------
//  hanoi(number of disks, source pillar, spare pillar, target pillar)
void hanoi(int d, vector<int>& a, vector<int>& b, vector<int>& c)
{
    if(d == 1)
    {
        c.push_back(a.back());
        a.pop_back();
        printTowers(a,b,c); 
    }
    else{
    hanoi(d-1,a,c,b);
    hanoi(1,a,b,c);
    hanoi(d-1,b,a,c);
    }
}
//------------
int main()
{
    int n = 3; 
    vector <int> A, B, C;
    A.reserve(n); B.reserve(n); C.reserve(n);

    for(int i=0; i<n; i++)
    {
        A.push_back(n-i);
    }    
    hanoi(n,A,B,C);   
    return 0;
}

Sample output :

 321 | 32 | 3  |    |    | 2  |    |    |
     |    | 1  | 3  | 21 | 3  | 1  |    |
     | 1  | 2  | 21 | 3  | 1  | 32 | 321|

Desired output :

 321 | 32 | 3  | 3  |    | 1  | 1  |    |
     |    | 2  | 21 | 21 | 2  |    |    |
     | 1  | 1  |    | 3  | 3  | 32 | 321|

Solution

  • You can use an extra cell in your vector that tell you what pillar is it. For example

    vector <int> A, B, C;
    A.reserve(n+1); B.reserve(n+1); C.reserve(n+1);
    A.push_back(-1);
    B.push_back(-2);
    C.push_back(-3);
    

    Now

    //add a new function to simplify code
    void printTowerId(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3, int id){  
        if(arr1[0] == id) printOut(arr1);
        if(arr2[0] == id) printOut(arr2);
        if(arr3[0] == id) printOut(arr3);
    }
    

    And your original function looks like

    void printTowers(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3)
    {
        printTowerId(arr1, arr2, arr3, -1);
        printTowerId(arr1, arr2, arr3, -2);
        printTowerId(arr1, arr2, arr3, -3);
    }
    

    Take care that in your recursion does not occupy the cell that you added