2016-04-08 286 views
0

这可能被认为是一个低眉问题。然而,我还没有找到任何代码或任何讨论如何在我的编程语言中讨论这个问题的论坛。C已经做了很多尝试,最终都是在对这些新阵列进行实际“硬编码”。垂直/水平翻转二维阵列

我想垂直,然后水平翻转2d数组。 这似乎很容易,只是系统地通过并操纵每一行和列的值。但是,如果我想讨论一个不仅仅是基本的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大小的数组)有什么人知道一个有效的方法来完成这个任务呢?

+0

想想如何翻转大小为“N”的数组。一旦完成,翻转一个marix几乎是一样的。 –

+0

请参阅我试图以此为例,但这纯粹是水平翻转阵列。我会再考虑一下。 – DancingDylan

+0

你的代码使用'i'作为列索引,并且根本不使用'j'。 – user3386109

回答

0

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

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); 
    } 
} 

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

+0

在您创建的VFlipArray函数中,FlipColumn(array,column,rows);给我一个不兼容的指针类型,指示(**数组**)给我的编译器错误。为什么会这样呢? **忽略这​​个**修复它,我看到了错误。感谢帮忙的人,我用这个代码作为基础,你的逻辑例子清楚地表明了我最初做错了什么。一定要记住这一点。 – DancingDylan

-1

你好你可以尝试一种简单的方法来翻转你的二维数组: -

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]进行翻页操作。

+0

你不是在翻转数组,而是在转置它 – ijverig