c - 垂直/水平翻转二维数组

标签 c arrays

这可能被认为是一个低俗的问题。然而,我还没有找到任何代码,也没有找到任何论坛讨论如何用我的编程语言 C 来解决这个问题。已经进行了大量的尝试,并且最终都以实际上“硬编码”新数组而告终。

我正在尝试垂直然后水平翻转二维数组。 这看起来很简单,只需系统地浏览并操作每一行和每一列的值即可。但是,如果我想要的数组不仅仅是基本的 3x3 数组,该怎么办?例如 11x11,还是 15x15?

**CODE SNIPPET:**

int array[3][3]= { {1,2,3},
                   {4,5,6},
                   {7,8,9} };

int vertFlip[3][3],
    horzFlip[3][3]; 

for(i = 0; i < rows; i++)
{
  for(j = 0; j < cols; j++)
  {
     vertFlip[0][i]= array[2][i];
     vertFlip[1][i]= array[1][i];
     vertFlip[2][i]= array[0][i];   
  }
} //and so on for horizontal, obviously my nested for loop was different. 

但是,如果这个数组更大(123x123 大小的数组)怎么办?有人知道完成此任务的有效方法吗?

最佳答案

我会从一个简单的方法开始。对于水平翻转:

int swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp; 
}

void FlipRow(int *row, int columns)
{
    // A row is a simple one dimensional array
    // just swap item 0 with item n-1, 1 with n-2, ...
    for (int index = 0; index < columns / 2; index++)
    {
        swap(row+index, row+columns-1-index);
    } 
}

void HFlipArray(int **array, int columns, int rows)
{
    for (int row = 0; row < rows; row++)
    {
        FlipRow(array[row], columns);
    }
}

对于垂直翻转,使用类似的方法:

// Reuse swap
void FlipColumn(int **array, int column, int rows)
{
    // Flip column 'column' of an array that has n rows.
    for (int row = 0; row < rows/2; row++)
    {
        swap(array[row]+column, array[rows-1-row]+column);
    }
}

void VFlipArray(int **array, int columns, int rows)
{
    for (int column = 0; column < columns; column++)
    {
        FlipColumn(array, column, rows);
    }
}

请注意,上面的代码更改了输入的内容。如果不需要,您可以修改代码以传入目标和源数组并相应地调整循环。

关于c - 垂直/水平翻转二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36491352/

相关文章:

c - 对具有 n 个间隔的 a 和 b 之间的函数进行积分

javascript - 具有 {key : 'theKey' , value: 'theValue' } 对象的数组

android - 如何在android中将json数组转换为字符串数组?

c++ - osx - 构建 POCO 库时出现链接错误

c - 在C中动态构造一个char

c - 将指针数组传递给函数并计算大小

javascript - 为什么 parseInt 与 Array.map 一起使用时返回 NaN?

javascript - 逗号分隔符多维数组

javascript - arguments 与 Array.prototype.slice.call(arguments,0)

c++ - 在 qt creator 中使用 winpcap 库