Towers of Hanoi: Difference between revisions

Line 196:
 
typedef struct { int *x, n; } tower;
tower *new_tower(int cap, int n)
{
tower *t = malloccalloc(1, sizeof(tower) + sizeof(int) * cap);
int i = 0;
tower *t = malloc(sizeof(tower) + sizeof(int) * cap);
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;
}
 
int height;
tower *t[3];
int i = 0height;
 
void movetext(int ny, towerint *fromi, towerint *tod, towerchar *vias)
void show_towers()
{
printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d);
int i, j, k;
while (d--) printf("\033[H"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(' ');
for(; k < height + t[ji]->x[height - t[i]; k->n++)] = d;
text(t[i]->n, i, d, "==");
putchar('#');
 
for(; k <= 2 * height; k++)
putchar(' ');
}
putchar('\n');
}
usleep(100000);
fflush(stdout);
}
 
int remove_disk(int i)
void move(int n, tower *from, tower *to, tower *via)
{
int diskd = t[i]->x[--t[i]->n];
text(t[i]->n + 1, i, d, " ");
if (n) {
return d;
move(n - 1, from, via, to);
}
 
void move(int n, int from, int to, int via)
disk = from->x[--from->n];
{
from->x[from->n] = 0;
if (!n) {return;
to->x[to->n++] = disk;
show_towers();
 
move(n - 1, viafrom, tovia, fromto);
add_disk(to, remove_disk(from));
}
move(n - 1, from, via, to, from);
}
 
int main(int c, char *v[])
{
printfputs("\033[H\033[J");
if (c <= 1 || (height = atoi(v[1])) <= 0) height = 8;
 
t[0]if (c <= new_tower1 || (height, height= atoi(v[1])) <= 0);
int height = 8;
t[1] = new_tower(height, 0);
for (c = 0; c < 3; c++) t[2c] = new_tower(height, 0);
for (c = height; c; c--) add_disk(0, c);
 
move(height, t[0], t[2], t[1]);
printf("\033[H\033[J");
show_towers();
move(height, t[0], t[2], t[1]);
 
text(1, 0, 1, "\n");
return 0;
}</lang>
Anonymous user