#include "Hanoi.h" #include using namespace std; Hanoi::Hanoi() { topA = 0; topB = 0; topC = 0; moves = 0; } Hanoi::~Hanoi(){} //fill source tower with number of disks void Hanoi::fillTowers(int disk) { int i = 1; topA = disk; while(disk > 0) { towerA[i] = disk; disk--; i++; } topB = 0; topC = 0; moves = 0; return; } void Hanoi::displayTowers() { int a = topA, b = topB, c = topC; int i = 9; cout << "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl; while(i > 0) { if(a > 0 && a >= i) { cout << " " << towerA[i] << flush; a--; } else cout << " " << flush; if(b > 0 && b >= i) { cout << "\t\t " << towerB[i] << flush; b--; } else cout << "\t\t " << flush; if(c > 0 && c >= i) { cout << "\t\t " << towerC[i] << flush; c--; } else cout << "\t\t " << flush; i--; cout << endl; } cout << "*A*\t\t*B*\t\t*C*" << endl; cout << "Source\t\tDestination\tSpare" << endl; cout << "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl; // cin.get(); cin.get(); } void Hanoi::moveDisks(char s, char d) { //when a is the source if(s == 'a' && d == 'b') { topB++; towerB[topB] = towerA[topA]; topA--; } if(s == 'a' && d == 'c') { topC++; towerC[topC] = towerA[topA]; topA--; } //when b is the source if(s == 'b' && d == 'a') { topA++; towerA[topA] = towerB[topB]; topB--; } if(s == 'b' && d == 'c') { topC++; towerC[topC] = towerB[topB]; topB--; } //when c is the source if(s == 'c' && d == 'a') { topA++; towerA[topA] = towerC[topC]; topC--; } if(s == 'c' && d == 'b') { topB++; towerB[topB] = towerC[topC]; topC--; } moves++; displayTowers(); } int Hanoi::solveTowers(int disks, char source, char dest, char spare) { if(disks == 1) moveDisks(source, dest); else { solveTowers(disks-1, source, spare, dest); solveTowers(1, source, dest, spare); solveTowers(disks-1, spare, dest, source); } return(moves); }