In: Computer Science
Tower of Hanoi problem
please use this code
#pragma once
#include
#include
#include
#include
using namespace std;
class TowersOfHanoi
{
friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers);
public:
//constructor
TowersOfHanoi();
//custom methods
unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout);
private:
//custom methods
void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux);
//temporary variable
unsigned _n_moves;
//data
const unsigned _n_towers;
stack* _tower;
};
#include "TowersOfHanoi.h"
//
ostream& operator<<(ostream& sink, const TowersOfHanoi& hanoi)
{
for (unsigned index = 0; index < hanoi._n_towers; index++)
{
sink << index + 1 << ": ";
stack temp;
while (!hanoi._tower[index].empty())
{
unsigned top = hanoi._tower[index].top();
hanoi._tower[index].pop();
temp.push(top);
}
while (!temp.empty())
{
unsigned top = temp.top();
temp.pop();
hanoi._tower[index].push(top);
sink << top << ' ';
}
sink << endl;
}
sink << "---" << endl;
return sink;
}
TowersOfHanoi::TowersOfHanoi(void)
:_n_towers(3)
{
_tower = NULL;
_n_moves = 0;
}
unsigned TowersOfHanoi::move(unsigned n_disks, ostream& sink)
{
if(n_disks < 1)
throw string("TowersOfHanoi:move - new-n-disks is 0 or negative");
_tower = new stack[_n_towers];
for(unsigned disk = n_disks; disk > 0; disk--)
_tower[0].push(disk);
_n_moves = 0;
sink << *this << endl;
move_aux(sink, n_disks, 0, 2, 1);
delete [] _tower;
return _n_moves;
}
void TowersOfHanoi::move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux)
{
if(n_disks > 1)
{
//move n -1 disks from source to auxilliary
//move_ 1 disk from source to destination
//mov n -1 disks from axuilliary to destination
}
else
{
unsigned top = _tower[srce].top();
_tower[srce].pop();
_tower[dest].push(top);
_n_moves++;
sink << *this << endl;
}
}
// testTowersOfHanoi.cpp : Defines the entry point for the console application.
//
#include
#include
#include "towersofhanoi.h"
using namespace std;
int main()
{
try
{
TowersOfHanoi towers;
for (unsigned n_disks = 1; n_disks <= 10; n_disks++)
{
cout << towers.move(n_disks) << " moves " << endl;
system("pause");
cout << endl << endl;
}
}
catch(string message)
{
cout << message << endl;
}
catch(...)
{
cout << "something is dreadfully wrong" << endl;
}
system("pause");
return 0;
}
|