2016-04-08 287 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