右移数组,C中无循环

时间:2018-10-07 18:42:45

标签: c arrays algorithm loops shift

我可以不使用循环就将数组[9]右移吗?

例如:

我有一个像这样的数组

{'h', 'e', 'l', 'l', 'o', '\0', '?', '?', '?'}

我想在其中更改数组

{'?', 'h', 'e', 'l', 'l', 'o', '\0', '?', '?'}

是否有不通过循环移动每个字符的解决方案?另外,递归也不是一个好的解决方案,因为我想节省算法时间。

2 个答案:

答案 0 :(得分:1)

最好的方法是像这样手动进行: aux = V [0] V [0] = V [1] ...... V [7] = V [8] V [8] =辅助 没有什么比手动实现更好的方式(关于优化)了。

答案 1 :(得分:0)

typedef union 
{
    uint64_t u;
    char c[8];
}silly_union;


typedef struct 
{
    size_t cpos;
    char buff[1024];
}even_worse;

typedef enum 
{
    RIGHT,
    LEFT,
    CENTRE,
}alignment;

even_worse *init(const char *str, alignment a)
{
    even_worse *ew = malloc(sizeof(*ew));
    if(ew)
    {
        switch(a)
        {
            case RIGHT:
                strcpy(ew -> buff[(ew -> cpos = sizeof(ew -> buff) - 2 - strlen(str))], str);
                break;
            case CENTRE:
                strcpy(ew -> buff[(ew -> cpos = sizeof(ew ->buff) / 2 - 1 - strlen(str) / 2)], str);
                break;
            case LEFT:
                strcpy(ew -> buff, str);
                ew -> cpos = 0;
                break;
        }
    }
    return ew;
}

char *shiftright(even_worse *ew)
{
    if(ew -> cpos)
    {
        ew -> cpos--;
        return ew -> buff[ew -> cpos];
    }
    return NULL;   
}

int shiftleft(even_worse *ew)
{
    if(ew -> cpos < sizeof(ew -> buff) - 1)
    {
        ew -> cpos++;
        return ew -> buff[ew -> cpos];
    }
    return NULL;   
}


int main()
{
    silly_union su = {.c = "hello"};

    su.u <<= 8; // little endian oppsite direction :)

    for(size_t i = 0; i < sizeof(su); i++)
    {
        printf("Char No: %zu = `%c` (%hhd)\n", i, su.c[i] > 32 && su.c[i] < 127 ? su.c[i] : ' ', su.c[i]);
    }

/*tests for even worse write yourself :)*/
}