HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Hanoi towers time exeeded

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
towersexeededhanoitime

Problem

I am having problem with a simple Hanoi tower program. I need to do something to reduce its time.

#include 
#include 

using namespace std;

int hanojus(int n, char a, char b, char c) {

    ofstream fr("hanoj.out",ios::app);
    if (n == 1)
        fr "  " >sk;
    hanojus(sk, 'A', 'B', 'C');
}

Solution

Try moving the ofstream outside of the method so that you're not creating it every time you make a recursive call.

Like this:

#include 
#include 

using namespace std;

int hanojus(int n, char a, char b, char c, ofstream& fr)
{
    if (n == 1)
        fr "  " >sk;
    hanojus(sk, 'A', 'B', 'C', fr);
}

Code Snippets

#include <stdio.h>
#include <fstream>

using namespace std;

int hanojus(int n, char a, char b, char c, ofstream& fr)
{
    if (n == 1)
        fr<<a<< " -> " <<c<<endl;
    else
    {
        hanojus(n-1, a, c, b, fr);
        fr<<a<< " -> " <<c<<endl;
        hanojus(n-1, b, a, c, fr);
    }
}

int main()
{
    ifstream fd("hanoj.in");
    ofstream fr("hanoj.out",ios::app);
    int sk;
    fd>>sk;
    hanojus(sk, 'A', 'B', 'C', fr);
}

Context

StackExchange Code Review Q#37514, answer score: 6

Revisions (0)

No revisions yet.