Last active
April 29, 2025 17:56
-
-
Save sunmeat/a7a417f01fdb10dadb31de0e4be010aa to your computer and use it in GitHub Desktop.
hanoj towers example C++
This file contains hidden or 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 <iostream> | |
| #include <windows.h> | |
| using namespace std; | |
| const int quantity = 5; | |
| int sterjen1[quantity]{}, sterjen2[quantity]{}, sterjen3[quantity]{}; | |
| void moveDisc(int from[], int to[]) | |
| { | |
| Sleep(100); | |
| //system("cls"); | |
| int posFrom = 0, posTo = quantity - 1; | |
| while (from[posFrom] == 0) | |
| posFrom++; | |
| for (int i = 0; i < quantity; i++) | |
| { | |
| if (to[i] != 0) | |
| { | |
| posTo = i - 1; | |
| break; | |
| } | |
| } | |
| to[posTo] = from[posFrom]; | |
| from[posFrom] = 0; | |
| } | |
| void printSterjni() | |
| { | |
| system("cls"); | |
| for (int i = 0; i < quantity; i++) | |
| { | |
| for (int s = 0; s < 3; s++) | |
| { | |
| int l = quantity - ((s == 0) ? sterjen1[i] : (s == 1) ? sterjen2[i] : sterjen3[i]); | |
| for (int x = 0; x < quantity * 2; x++) | |
| { | |
| if (x >= l && x < quantity * 2 - l) | |
| cout << (char)178; | |
| else | |
| cout << " "; | |
| } | |
| } | |
| cout << endl; | |
| } | |
| } | |
| void hanoj(int n, int st1[], int st2[], int st3[]) | |
| { | |
| if (n == 1) | |
| { | |
| moveDisc(st1, st2); | |
| printSterjni(); | |
| } | |
| else if (n > 1) | |
| { | |
| hanoj(n - 1, st1, st3, st2); | |
| moveDisc(st1, st2); | |
| printSterjni(); | |
| hanoj(n - 1, st3, st2, st1); | |
| } | |
| } | |
| int main() | |
| { | |
| system("title Hanoj Towers"); | |
| for (int i = 0; i < quantity; i++) | |
| sterjen1[i] = i + 1; | |
| printSterjni(); | |
| hanoj(quantity, sterjen1, sterjen3, sterjen2); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment