2017-10-17 21 views
0

根據m & n的值,我需要一系列for循環來返回如下所示的框。用相同值的周界打印一盒數字

應該輸出:

1 1 1 1 1 1 1  
1 2 2 2 2 2 1  
1 2 3 3 3 2 1 
1 2 2 2 2 2 1 
1 1 1 1 1 1 1 

下面是到目前爲止我的代碼,它使用了一系列的循環半分割盒,要麼上升或下降的值列和行兩個。我卡住的地方是試圖找到一種方法來爲這些值創建這些周界。另外需要注意的是,這應該能夠在不使用任何if語句的情況下工作。

int m = 5; //column value 
int n = 7; //row value 
int column; 

for (int row = 0; row <= (m/2); row++) { 
    //Ascending 
    for (column = 1; column < (n/2); column++) { 
     int outputNumber = row + 1; 
     System.out.print(outputNumber + " "); 
    } 

    //Fixed 
    do { 
     int outputNumber = row + 1; 
     System.out.print(outputNumber + " "); 
    } 
    while (column < 0); 

    //Descending 
    for (column = n/2; column >= 0; column--) { 
     int outputNumber = row + 1; 
     System.out.print(outputNumber + " "); 
    } 
    System.out.println(); 
} 

for (int row = m/2; row > 0; row--) { 
    for (column = 1; column <= n; column++) { 
     System.out.print(row + " "); 
    } 
    System.out.println(); 
} 

上面的代碼電流輸出:

1 1 1 1 1 1 1  
2 2 2 2 2 2 2  
3 3 3 3 3 3 3  
2 2 2 2 2 2 2  
1 1 1 1 1 1 1 
+0

那麼打印的數字應該代表退出矩陣所需的最小「步數」? –

+0

當矩陣實際上是一個數組(例如,5 x 1或1 x 5)時,輸出應該是什麼? – jhenderson2099

+0

循環做什麼?它看起來像列總是> = 1,所以它只會執行一次 – phflack

回答

0

這裏是我的結果。我知道這有點複雜而且寫得很快,但它解決了你的問題。我還與其他數字測試它:

int m = 5; //column value 
int n = 7; //row value 

for (int i = 0; i < m/2 + 1; i++) { 
    for (int j = 0; j < i + 1; j++) { 
     System.out.print(j + 1 + " "); 
    } 
    for (int j = 0; j < n - ((i + 1) * 2); j++) { 
     System.out.print(i + 1 + " "); 
    } 
    for (int j = 0; j < i + 1; j++) { 
     System.out.print(i + 1 - j + " "); 
    } 

    System.out.println(""); 
} 

for (int i = m/2 + 1; i < m; i++) { 
    for (int j = 0; j < m - i; j++) { 
     System.out.print(j + 1 + " "); 
    } 
    for(int j = 0; j < n - (m - i) * 2; j++) { 
     System.out.print(m-i + " "); 
    } 
    for(int j = 0; j < m - i; j++) { 
     System.out.print(m - i - j + " "); 
    } 

    System.out.println(""); 
} 
0

假設我的理解是正確的,因爲周邊的瓷磚應該是1,隨後每瓦應該顯示的「階梯」的最低數量,將採取從外部那裏矩陣。

我個人很難想象/遵循您的解決方案,所以我不確定我的建議是否會與您的理解相吻合。

首先,讓我們把這個矩陣的構造與這個矩陣的打印分開。我認爲這讓事情保持整潔,但那是我的風格。

假設你的矩陣中有c列和r行。因此,我們將使用嵌套for循環遍歷每個單元格。

for (int r = 0; r < rows; r++) { 
    for (int c = 0; c < columns; c++) { 
     int distanceToEdgeOfRow = Math.abs(rows - (r - rows)); //this finds the number of steps to the nearest row end 
     int distanceToEdgeOfColumn = Math.abs(columns - (c - columns)); //this find the number of steps to the nearest column end 

     int shortestPath = Math.min(distanceToEdgeOfColumn, distanceToEdgeOfRow); //is it shorter to take the closest row exit or column exit? 

     //the shortestPath is still off by one, so we need to add 1 to shortestPath to see what should be printed on this tile 
     matrix[r][c] = shortestPath + 1; 
    } 
} 
相關問題