河内的塔,跑步的问题 [英] Towers of hanoi, problem with running

查看:102
本文介绍了河内的塔,跑步的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上搜索了这个,但由于某种原因它不起作用*这可能是因为那里的usleep和fflush。

介意向我解释他们做了什么 - 或者更好地给我一些我可以替换的东西?



I searched this in the internet and for some reason it doesn''t work *which is probably because of the "usleep" and "fflush" there.
mind explaining to me what they do--or better yet give me something that I can replace those with?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct { int *x, n; } tower;
tower *new_tower(int cap)
{
    tower *t = calloc(1, sizeof(tower) + sizeof(int) * cap);
    t->x = (int*)(t + 1);
    return t;
}

tower *t[3];
int height;

void text(int y, int i, int d, const char *s)
{
    printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d);
    while (d--) printf("%s", s);
}

void add_disk(int i, int d)
{
    t[i]->x[t[i]->n++] = d;
    text(t[i]->n, i, d, "==");

    usleep(100000);
    fflush(stdout);
}

int remove_disk(int i)
{
    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)
{
    if (!n) return;

    move(n - 1, from, via, to);
    add_disk(to, remove_disk(from));
    move(n - 1, via, to, from);
}

int main(int c, char *v[])
{
    puts("\033[H\033[J");

    if (c <= 1 || (height = atoi(v[1])) <= 0)
        height = 8;
    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);

    text(1, 0, 1, "\n");
    return 0;
}

推荐答案

Google可以:

usleep功能 [ ^ ]

fflush功能 [ ^ ]



前者是让你看到它前进到下一个运动,第二个是确保输出全部写入(无论如何都应该是不必要的)。



我不能建议替换,因为我不知道你试图在哪个环境中运行它!
Google can:
usleep function[^]
fflush function[^]

The former is there to let you see the movement before it goes on to the next, and the second to make sure the output is all written (should be unnecessary anyway).

I can''t suggest replacements, as I have no idea what environment you are trying to run this in!


这个小程序使用所谓的ANSI屏幕控制序列。例如

This little program uses so-called ANSI screen control sequences. For example does the
ESC n ; m H 



序列将光标定位到行n,列m。在过去的好时光中使用这些控制序列来控制基于字符的屏幕上的光标和其他属性。



如果输出设备不理解那些控制序列它只是打印带标签的字符。这可能是你没有看到任何东西的原因。 usleep和fflush对我来说很好看。根据您的平台查找了解ANSI控制序列的shell,您将没事。


sequence position the cursor to row n, column m. These control sequences were used in the good old days to control the cursor and other properties on a character-based screen.

If the output device doesn''t understand those control sequences it just prints garbeled characters. So that may be the reason you are not seeing anything. The usleep and fflush look ok to me. Depending on your platform look for shell that understands ANSI control sequences and you will be fine.


这篇关于河内的塔,跑步的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆