Towers of Hanoi: Difference between revisions
Content added Content deleted
Line 196: | Line 196: | ||
typedef struct { int *x, n; } tower; |
typedef struct { int *x, n; } tower; |
||
tower *new_tower(int cap |
tower *new_tower(int cap) |
||
{ |
{ |
||
⚫ | |||
⚫ | |||
⚫ | |||
t->x = (int*)(t + 1); |
t->x = (int*)(t + 1); |
||
t->n = 0; |
|||
while (i < n) t->x[t->n++] = n - i++; |
|||
while (i < cap) t->x[i++] = 0; |
|||
return t; |
return t; |
||
} |
} |
||
⚫ | |||
tower *t[3]; |
tower *t[3]; |
||
⚫ | |||
⚫ | |||
void show_towers() |
|||
{ |
{ |
||
printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d); |
|||
int i, j, k; |
|||
printf( |
while (d--) printf(s); |
||
⚫ | |||
for (i = 1; i <= height; i++) { |
|||
for (j = 0; j < 3; j++) { |
|||
void add_disk(int i, int d) |
|||
for(k = 0; k <= height - t[j]->x[height - i]; k++) |
|||
{ |
|||
putchar(' '); |
|||
t[i]->x[t[i]->n++] = d; |
|||
text(t[i]->n, i, d, "=="); |
|||
putchar('#'); |
|||
for(; k <= 2 * height; k++) |
|||
putchar(' '); |
|||
} |
|||
putchar('\n'); |
|||
⚫ | |||
usleep(100000); |
usleep(100000); |
||
fflush(stdout); |
|||
} |
} |
||
int remove_disk(int i) |
|||
⚫ | |||
{ |
{ |
||
int |
int d = t[i]->x[--t[i]->n]; |
||
text(t[i]->n + 1, i, d, " "); |
|||
⚫ | |||
return d; |
|||
⚫ | |||
⚫ | |||
void move(int n, int from, int to, int via) |
|||
disk = from->x[--from->n]; |
|||
{ |
|||
from->x[from->n] = 0; |
|||
⚫ | |||
to->x[to->n++] = disk; |
|||
show_towers(); |
|||
move(n - 1, from, via, to); |
|||
add_disk(to, remove_disk(from)); |
|||
⚫ | |||
⚫ | |||
} |
} |
||
int main(int c, char *v[]) |
int main(int c, char *v[]) |
||
{ |
{ |
||
⚫ | |||
if (c <= 1 || (height = atoi(v[1])) <= 0) height = 8; |
|||
if (c <= 1 || (height = atoi(v[1])) <= 0) |
|||
⚫ | |||
t[1] = new_tower(height, 0); |
|||
t[ |
for (c = 0; c < 3; c++) t[c] = new_tower(height); |
||
for (c = height; c; c--) add_disk(0, c); |
|||
⚫ | |||
⚫ | |||
show_towers(); |
|||
⚫ | |||
text(1, 0, 1, "\n"); |
|||
return 0; |
return 0; |
||
}</lang> |
}</lang> |