[ create a new paste ] login | about

Link: http://codepad.org/k3UBIyiC    [ raw code | output | fork ]

C++, pasted on Apr 5:
#include <iostream>

int lineNumber;
enum pole { onleft, middle, onright };

void towersOfHanoi (int n, pole start, pole temporary, pole destination)
{
   if (n > 0) {
      towersOfHanoi(n-1, start, destination, temporary);
      lineNumber++;
      std::cout << lineNumber << ". Move the top from the " << start
                << " pole to the " << destination << " pole.\n";
      towersOfHanoi(n-1, temporary, start, destination);
   }   
}

void towersOfHanoi(
   int d)
{
   lineNumber = 0;
   towersOfHanoi(d, onleft, middle, onright);
}


std::ostream& operator<< (
   std::ostream& os, 
   pole p)
{
   switch(p) {
   case onleft:  os << "left";    break;
   case middle:  os << "middle";  break;
   case onright: os << "right";   break;
   }   
   return os; 
}

int main()
{
   towersOfHanoi(3);

   return 0;
}


Output:
1
2
3
4
5
6
7
1. Move the top from the 0 pole to the 2 pole.
2. Move the top from the 0 pole to the 1 pole.
3. Move the top from the 2 pole to the 1 pole.
4. Move the top from the 0 pole to the 2 pole.
5. Move the top from the 1 pole to the 0 pole.
6. Move the top from the 1 pole to the 2 pole.
7. Move the top from the 0 pole to the 2 pole.


Create a new paste based on this one


Comments: