c-垂直/水平翻转2d阵列



这可能被认为是一个低调的问题。然而,我还没有找到任何代码,也没有找到任何论坛讨论如何在我的编程语言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);
    }
}

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

你好,你可以尝试一种简单的方法来transpose你的2d数组:-

int ar[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int i,j,ar1[3][3];
for(i = 0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
       ar1[i][j] = ar[j][i];
    }
}

正如您所看到的,您只需要将循环迭代到您的数组长度,然后在循环ar1[i][j] = ar[j][i]中执行翻转操作。

模板解决方案

适用于ints、floats、doubles的阵列。。。

template <class t>
void flip_horizontal(const int nrows, const int ncols, t* data)  // flips left-right
{
    for (int rr = 0; rr < nrows; rr++)
    {
        for (int cc = 0; cc < ncols/2; cc++)
        {
            int ccInv = ncols - 1 - cc;
            std::swap<t>(data[rr * ncols + cc], data[rr * ncols + ccInv]);
        }
    }
}
template <class t>
void flip_vertical(const int nrows, const int ncols, t* data)  // flips: bottom-up
{
    for (int cc = 0; cc < ncols; cc++)
    {
        for (int rr = 0; rr < nrows/2; rr++)
        {
            int rrInv = nrows - 1 - rr;
            std::swap<t>(data[rr * ncols + cc], data[rrInv * ncols + cc]);
        }
    }
}

最新更新