在 C 中切换数组的元素

Switching an array's elements in C

所以我想切换一个数组的元素与 32 个整数 "n" 次。

所有元素都应该在下一个位置,最后一个应该在第一个。

我试过这样的事情:

while(scanf("%d", &n) != EOF)
{
    for(int j=0; j<n; j++)
    for(int i=1; i<31; i++)
    {
        t[0]=t[31];
        tmp=t[i];
        t[i]=t[i+1];
    }
}

我不确定如何使用 tmp 变量来解决这个问题。

这是数组的元素:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

如果 n=1:

它应该看起来像这样

32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

你的交换是错误的,它应该是这样的:

char temp = t[i];
t[i] = t[i + 1];
t[i + 1] = temp;

此外,如果您想要这样的无限循环,我建议跳过 scanf 中的空格,如下所示:

while (scanf(" %d", &n) == 1) // note the space before %d

总而言之,它可能是这样的:

int main(int argc, char** argv) {
    char t[33] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"; // 33 elements to leave space for '[=12=]'
    int n;
    while (scanf(" %d", &n) == 1)
    {
        for (int j = 0; j < n; j++)
            for (int i = 0; i < 31; i++)
            {
                char temp = t[i];
                t[i] = t[i + 1];
                t[i + 1] = temp;
            }
        printf("string: %s\n", t);
    }
    return 0;
}

以下不是对您的代码的编辑,而是运行时间为 O(n) 的更有效的解决方案:

void rightshift(char array[LENGTH])
{
    int i, next = array[0];

    for (i = 1; i < LENGTH; i++)
    {
        char temp = array[i];
        array[i] = next;
        next = temp;
    }

    array[0] = next;
}

由于元素每次移动 1 个位置,您可以提高效率。 您不需要为每个元素使用临时变量,而只需为 first/last 使用临时变量。 您不需要交换每对相邻元素。

void rotate_by_1(char array[], size_t elem)
{
    int i;

#ifdef ROTATE_LEFT
    // Rotate in one direction...
    char tmp = array[0];
    for (i = 0; i < elem-1; i++)
    {
        array[i] = array[i+1];
    }
    array[elem-1] = tmp;
#endif

#ifdef ROTATE_RIGHT
    // Rotate in the other direction...
    char tmp = array[elem-1];
    for (i = elem-1; i > 0; i--)
    {
        array[i] = array[i-1];
    }
    array[0] = tmp;
#endif
}

未测试...

首先请注意,要将32个元素的数组旋转n次,只需要旋转n % 32次。作为替代方案,可能不是最快的,对于已经提供的解决方案,下面的代码以相反的顺序复制原始数组的两个内存卡盘,这等于右移数组 n 次。

#define LEN 32
#define NUMBER_OF_ROTATIONS 56

int array_to_rotate[LEN];

int* tmp = malloc(sizeof(int) * LEN);

int n = NUMBER_OF_ROTATIONS % LEN;

// copying the last n elements of array_to_rotate to the beginning of tmp array
memcpy(tmp, (array_to_rotate + LEN - n), n * sizeof(int));

// copying first (LEN - n) elements of array_to_rotate behind the elements already copied to tmp array
memcpy((tmp + n), array, (LEN - n) * sizeof(int));

//replacing the original array with the one obtained after rotation n times
memcpy(array, tmp, sizeof(int) * LEN));

free(tmp);