Created
July 1, 2013 02:34
-
-
Save ygabo/5898011 to your computer and use it in GitHub Desktop.
Towers of Hanoi solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "hanoi.hpp" | |
Hanoi::Hanoi(){ | |
x = 4; | |
for( int i = x-1; i >= 0; --i) | |
peg[0].push(i); | |
} | |
Hanoi::Hanoi(int n){ | |
x = n; | |
for( int i = x-1; i >= 0; --i) | |
peg[0].push(i); | |
} | |
void Hanoi::reset(){ | |
while(!peg[0].empty()) peg[0].pop(); | |
while(!peg[1].empty()) peg[1].pop(); | |
while(!peg[2].empty()) peg[2].pop(); | |
for( int i = x-1; i >= 0; --i) | |
peg[0].push(i); | |
} | |
void Hanoi::solve(int n, int src, int temp, int dest){ | |
if(n < 1 ) return; | |
solve(n-1, src, dest, temp); | |
int num = peg[src].top(); | |
peg[src].pop(); | |
peg[dest].push(num); | |
solve(n-1, temp, src, dest); | |
} | |
void Hanoi::print(){ | |
stack<int> tempstack; | |
tempstack = peg[0]; | |
while(!tempstack.empty()){ | |
cout << tempstack.top() << " "; | |
tempstack.pop(); | |
} | |
cout << "|" << endl; | |
tempstack = peg[1]; | |
while(!tempstack.empty()){ | |
cout << tempstack.top() << " "; | |
tempstack.pop(); | |
} | |
tempstack = peg[2]; | |
cout << "|" << endl; | |
while(!tempstack.empty()){ | |
cout << tempstack.top() << " "; | |
tempstack.pop(); | |
} | |
cout << "|" << endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef HANOI_HPP | |
#define HANOI_HPP | |
#include <stack> | |
#include <iostream> | |
using namespace std; | |
class Hanoi{ | |
public: | |
Hanoi(); | |
Hanoi(int x); | |
void reset(); | |
void solve(int n, int src, int temp, int dest); | |
void print(); | |
private: | |
stack<int> peg[3]; | |
int x; | |
}; | |
#endif // HANOI_HPP |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "hanoi.hpp" | |
int main(){ | |
Hanoi han; | |
han.solve(4, 0, 1, 2); | |
han.print(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment