Skip to content

Instantly share code, notes, and snippets.

@andiac
Last active October 21, 2018 13:36
Show Gist options
  • Save andiac/eaccb1410abbcfd300567f27448680e1 to your computer and use it in GitHub Desktop.
Save andiac/eaccb1410abbcfd300567f27448680e1 to your computer and use it in GitHub Desktop.
Hanoi Tower
#include <stdio.h>
struct stack {
int v[100];
int top;
} stacks[3];
int N;
void push(struct stack * a, int v) {
(*a).v[(*a).top++] = v;
}
int pop(struct stack * a) {
return (*a).v[((*a).top--)-1];
}
void printblock(int value) {
for (int i=0; i<N-value; ++i) printf(" ");
for (int i=0; i<value; ++i) printf("=");
for (int i=0; i<value; ++i) printf("=");
for (int i=0; i<N-value; ++i) printf(" ");
}
void printline(int idx) {
printf("|");
for (int i=0; i<3; ++i) {
if (idx < stacks[i].top)
printblock(stacks[i].v[idx]);
else
printblock(0);
printf("|");
}
printf("\n");
}
void print() {
for (int i=N-1; i>=0; i--)
printline(i);
for (int i=0; i<N*2*3 + 4; ++i) printf("-");
printf("\n");
}
void hanoi(int N, struct stack * a, struct stack * b, struct stack * c) {
if (N > 0) {
hanoi(N-1, a, c, b);
push(c, pop(a));
print();
hanoi(N-1, b, a, c);
}
}
int main() {
scanf("%d", &N);
for (int i=0; i<N; ++i) {
push(stacks, N-i);
}
print();
hanoi(N, &stacks[0], &stacks[1], &stacks[2]);
}
/*
For example, N=3:
| == | | |
| ==== | | |
|======| | |
----------------------
| | | |
| ==== | | |
|======| | == |
----------------------
| | | |
| | | |
|======| ==== | == |
----------------------
| | | |
| | == | |
|======| ==== | |
----------------------
| | | |
| | == | |
| | ==== |======|
----------------------
| | | |
| | | |
| == | ==== |======|
----------------------
| | | |
| | | ==== |
| == | |======|
----------------------
| | | == |
| | | ==== |
| | |======|
----------------------
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment