Advertisement
skb50bd

TowerOfHanoi

Aug 4th, 2016
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. bool confirm() {
  6.     char ch = '\o';
  7.     while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N')
  8.         cin >> ch;
  9.     if (ch == 'y' || ch == 'Y')
  10.         return true;
  11.     else
  12.         return false;
  13. }
  14.  
  15.  
  16. void hanoi(int n, char A, char B, char C) {
  17.     if (n == 1) {
  18.         cout << "[Disk: 1]\t" << A << " -> " << B << endl;
  19.         return;
  20.     }
  21.     else {
  22.         hanoi(n - 1, A, C, B);
  23.         cout << "[Disk: " << n << "]\t" << A << " -> " << B << endl;
  24.         hanoi(n - 1, C, B, A);
  25.     }
  26. }
  27.  
  28. int main() {
  29.     int n;
  30.     cout << "Enter the Number of Disks: ";
  31.     cin >> n;
  32.     cout << "Number of Swaps: " << pow(2, n) - 1 << endl;
  33.     cout << "Do you want to Display the Swaps? (y/n): ";
  34.     if (confirm())
  35.         hanoi(n, 'A', 'B', 'C'); //initially all the Disks are on Tower A
  36.  
  37.     cout << endl << "Exiting..." << endl;
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement