In: Computer Science
Only 1 file has changed and I have given you the updated the
changed file. Please use other files as is.
Please do rate the answer if it helped. Thank you.
TowersOfHanoi.cpp
------------------
#include "TowersOfHanoi.h"
//
ostream& operator<<(ostream& sink, const
TowersOfHanoi& hanoi)
{
for (unsigned index = 0; index < hanoi._n_towers; index++)
{
sink << index + 1 << ": ";
stack<unsigned> 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<unsigned>[_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_aux(sink, n_disks-1, srce, aux, dest);
//move_ 1 disk from source to destination
move_aux(sink, 1, srce, dest, aux);
//mov n -1 disks from axuilliary to destination
move_aux(sink,n_disks-1, aux,dest, srce);
}
else
{
unsigned top = _tower[srce].top();
_tower[srce].pop();
_tower[dest].push(top);
_n_moves++;
sink << *this << endl;
}
}