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, int n)
tower *new_tower(int cap)
{
{
tower *t = calloc(1, sizeof(tower) + sizeof(int) * cap);
int i = 0;
tower *t = malloc(sizeof(tower) + sizeof(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;
}
}


int height;
tower *t[3];
tower *t[3];
int height;


void text(int y, int i, int d, char *s)
void show_towers()
{
{
printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d);
int i, j, k;
printf("\033[H");
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(' ');
for(; k < height + t[j]->x[height - i]; k++)
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)
void move(int n, tower *from, tower *to, tower *via)
{
{
int disk;
int d = 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, via, to, from);
move(n - 1, from, via, to);
add_disk(to, remove_disk(from));
}
move(n - 1, via, to, from);
}
}


int main(int c, char *v[])
int main(int c, char *v[])
{
{
puts("\033[H\033[J");
if (c <= 1 || (height = atoi(v[1])) <= 0) height = 8;


t[0] = new_tower(height, height);
if (c <= 1 || (height = atoi(v[1])) <= 0)
height = 8;
t[1] = new_tower(height, 0);
t[2] = new_tower(height, 0);
for (c = 0; c < 3; c++) t[c] = new_tower(height);
for (c = height; c; c--) add_disk(0, c);


move(height, 0, 2, 1);
printf("\033[H\033[J");
show_towers();
move(height, t[0], t[2], t[1]);


text(1, 0, 1, "\n");
return 0;
return 0;
}</lang>
}</lang>