2016-11-16 60 views
0

我試圖讓這個號碼模式創造了多個模式

Input: 7 
Output: 
1 1 1 1 1 1 1 
1 2 2 2 2 2 1 
1 2 3 3 3 2 1 
1 2 3 4 3 2 1 
1 2 3 3 3 2 1 
1 2 2 2 2 2 1 
1 1 1 1 1 1 1 

但我無法弄清楚如何使它這樣,任何建議如何使這一模式?

我迄今爲止代碼:

int n, temp1, temp2,i,j; 
cin >> n; 
for (i = 1; i <= n; i++) { 
    for (j = 1; j <= n; j++) { 
     temp1 = j; 
     temp2 = n-j+1; 
     if (temp1 < temp2) cout << temp1; 
     else cout << temp2; 
    } 
    cout << endl; 
} 

輸出到目前爲止提前

1 2 3 4 3 2 1 
1 2 3 4 3 2 1 
1 2 3 4 3 2 1 
1 2 3 4 3 2 1 
1 2 3 4 3 2 1 
1 2 3 4 3 2 1 
1 2 3 4 3 2 1 

感謝。

+0

什麼是輸出這麼遠嗎? – Bathsheba

+0

嘗試寫下你將如何構建這個英文,然後將其轉換爲代碼。 –

+0

n的內部循環函數需要工作。正如Eli寫的,首先定義你的函數,然後編碼。 –

回答

1

我希望這個代碼(工作)可能會給你一個關於實現的更好的想法。

int main() { 

int n; 
cin >> n; 
int arr[n][n]; 

//Numbers in the grid vary from 1 - (n/2 + 1) 
for(int i = 0; i <= n/2; i++) { 
    //Start filling the array in squares 
    //Like fill the outer square with 1 first followed by 2... 
    for(int j = i; j < n - i; j++) { 

     arr[i][j] = i + 1; 
     arr[n - 1 - i][j] = i + 1; 
     arr[j][i] = i + 1; 
     arr[j][n - 1 - i] = i + 1; 
    } 
} 
+0

這是一個非常簡單的實現。謝謝,現在我知道我會做什麼。 –

1

解決該問題最主要的是該正方形分成4個象限:

 
---n--> 
111|222 | 
111|222 | 
111|222 | 
------- n 
333|444 | 
333|444 | 
333|444 v 

每個象限可帶有限制:

1 - row <= (n + 1)/2 && column <= (n + 1)/2 
2 - row <= (n + 1)/2 && column > (n + 1)/2 
3 - row > (n + 1)/2 && column <= (n + 1)/2 
4 - row > (n + 1)/2 && column > (n + 1)/2 

然後每象限具有被分成兩片

 
\ |/
\ |/
    \|/ 
------- 
    /|\ 
/| \ 
/| \ 
現在使用的行或列的索引相應

column_index = row_index 
column_index = (n + 1) - row_index 

你只需要檢查,如果當前的「細胞」是在以上的對角線之一,並且:

這些對角線可以用方程來描述。當然,如果行或列索引大於(n + 1)/ 2,那麼你必須通過從n中減去它來進行調整。

如果你明白這一點,編寫你自己的代碼應該不成問題。如果您必須立即打印所有內容而不將其存儲在某種陣列中,這是個好主意。如果你可以使用數組,那麼@ baymaxx解決方案會更清晰。

這是我的代碼,如果你想比較的實現:

#include <iostream> 

int main() { 
    int n; 
    std::cin >> n; 

    for (int row_index = 1; row_index <= n; row_index++) { 
     for (int column_index = 1; column_index <= n; column_index++) { 
      if (row_index <= (n + 1)/2 && column_index <= (n + 1)/2) { 
       if (column_index < row_index) { 
        std::cout << column_index << " "; 
       } else { 
        std::cout << row_index << " "; 
       } 
      } else if (row_index <= (n + 1)/2 && column_index > (n + 1)/2) { 
       if (column_index < (n + 1) - row_index) { 
        std::cout << row_index << " "; 
       } else { 
        std::cout << (n + 1) - column_index << " "; 
       } 
      } else if (row_index > (n + 1)/2 && column_index <= (n + 1)/2) { 
       if (column_index < (n + 1) - row_index) { 
        std::cout << column_index << " "; 
       } else { 
        std::cout << (n + 1) - row_index << " "; 
       } 
      } else { 
       if (column_index > row_index) { 
        std::cout << (n + 1) - column_index << " "; 
       } else { 
        std::cout << (n + 1) - row_index << " "; 
       } 
      } 
     } 
     std::cout << "\n"; 
    } 
} 
+0

謝謝先生,我現在明白如何去做 –