Skip to content

Instantly share code, notes, and snippets.

@ygabo
Created July 1, 2013 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ygabo/5898011 to your computer and use it in GitHub Desktop.
Save ygabo/5898011 to your computer and use it in GitHub Desktop.
Towers of Hanoi solver
#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;
}
#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
#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