samedi 29 septembre 2018

towers of hanoi recursion not working correctly

I am trying to do towers of hanoi with 7 disks using recursion for a school project, I'm not sure what the problem is but the output is completely wrong. I assume it has something to do with the moveDisk() function but I'm unable to find the issue. The number of moves is correct. Any help would be much appreciated. Here is my code and please leave a comment if you have any questions:

//#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <cassert>

using namespace std;

struct Peg
{
    vector<int> peg;
    string name;
};

void loadDisk(int diskNum, vector<int> &startPeg)
{
assert(startPeg.size() == 0);
for (int i = diskNum; i > 0; i--)
{
    startPeg.push_back(i);
}
}

void printPeg(int diskNum, vector<int> peg, string name)
{
cout << name << endl;
assert(peg.size() >= 0);
if (peg.size() > 0)
{
    for (unsigned int i = 0; i < peg.size(); i++)
    {
        cout << peg[i];
    }
}
cout << endl << endl;
}

void moveDisk(vector<int> &startPeg, vector<int> &goalPeg)
{
if (goalPeg.size() == 0)
{
    int temp = startPeg.back();
    startPeg.pop_back();
    goalPeg.push_back(temp);
}
}

int hanoi(int diskNum, vector<int> &startPeg, vector<int> &goalPeg, vector<int> &tempPeg)
{
int count = 0;
if (diskNum == 0)
{
    moveDisk(startPeg, goalPeg);
}
else
{
    count = hanoi(diskNum - 1, startPeg, tempPeg, goalPeg);
    moveDisk(startPeg, goalPeg); 
    count++;
    count += hanoi(diskNum - 1, tempPeg, goalPeg, startPeg);
}
return count;
}



int main()
{
Peg startPeg, tempPeg, goalPeg;
startPeg.name = "Start";
tempPeg.name = "Temp";
goalPeg.name = "Goal";
int diskNum = 7;

loadDisk(diskNum, startPeg.peg);

cout << "Starting Conditions with three pegs: " << endl;

printPeg(diskNum, startPeg.peg, startPeg.name);
printPeg(diskNum, tempPeg.peg, tempPeg.name);
printPeg(diskNum, goalPeg.peg, goalPeg.name);

int moveCount = hanoi(diskNum, startPeg.peg, tempPeg.peg, goalPeg.peg);

cout << "End Conditions with three pegs: " << endl;

printPeg(diskNum, startPeg.peg, startPeg.name);
printPeg(diskNum, tempPeg.peg, tempPeg.name);
printPeg(diskNum, goalPeg.peg, goalPeg.name);

cout << moveCount << " total moves were taken." << endl;

system("pause");
return 0;
}

and the current output is : Starting Conditions with three pegs: Start 7654321

Temp

Goal

End Conditions with three pegs: Start 76543

Temp 2

Goal 1

127 total moves were taken.

Aucun commentaire:

Enregistrer un commentaire