Towers of Hanoi algorithm without printing anything to terminal window

316 views Asked by At

The typical Towers of Hanoi Problem Solver would be the following:

void hanoi(int diskNumber , int start, int temp, int finish)
{
    if(diskNumber == 1)
    {
        cout<< " Move Disk " << diskNumber<<" from " << start <<" to "<< finish<<endl;
    }
    else
    {
        hanoi(diskNumber-1,start,temp,finish);
        cout<<"Move Disk from " << start <<" to "<<finish<<endl;
        hanoi(diskNumber - 1,temp,start,finish);
    }
}

But what I want to do is calculating the time that the algorithm runs. thus:

int main
{
    //Hanoi:
    cout<<"Hanoi Tower Problem:"<<endl;
    //3 Disks:
    clock_t htimer3 = clock();
    hanoi(3, 1,2,3);
    cout<<"CPU Time for n = 3 is: "
    <<clock() - htimer3/CLOCKS_PER_SEC<<endl;
    //6 Disks:
    clock_t htimer6 = clock();
    hanoi(6, 1,2,3);
    cout<<"CPU Time for n = 6 is: "
    <<clock() - htimer6/CLOCKS_PER_SEC<<endl;
    //9 Disks:
    clock_t htimer9 = clock();
    hanoi(9, 1,2,3);
    cout<<"CPU Time for n = 9 is: "
    <<clock() - htimer9/CLOCKS_PER_SEC<<endl;
    //12 Disks:
    clock_t htimer12 = clock();
    hanoi(12, 1,2,3);
    cout<<"CPU Time for n = 12 is: "
    <<clock() - htimer12/CLOCKS_PER_SEC<<endl;
    //15 Disks:
    clock_t htimer15 = clock();
    hanoi(15, 1,2,3);
    cout<<"CPU Time for n = 15 is: "
    <<clock() - htimer15/CLOCKS_PER_SEC<<endl;
    //End of Hanoi Tower Problem
    return 0;
}

the problem here is that for example if I set the diskNumber = 15, the code's gonna run for 32767 times which will fill out the terminal window and I'll lose generated lines that comes before it (I have to calculate some other algorithms like bubble sort quick sort etc. I'm gonna use the numbers to draw a chart later to represent their Big O, i.e: Big O of Towers of Hanoi Algorithm is 2^n) . To solve this problem I modified the code:

void hanoi(int diskSize, int start, int finish, int temp)
{
  if(diskSize == 1)
    {
        return;
    }
    else
    {
        hanoi(diskSize - 1, start, temp, finish);
        hanoi(diskSize - 1, temp, finish, start);
    }
}

My main question: does the modified code, take the same running time as if it was the original algorithm? if not, what should do? any suggestions?

1

There are 1 answers

5
KodingKid On BEST ANSWER

Yes, the time complexity of your modified code is same as the previous one since cout takes constant time. So your running time will not be affected much (granularity would be in order of nanoseconds) considering the stream you're writing to.

I would recomment redirecting the output to a file. For example:

./executable > FileName