我試圖弄清楚如何完成這個問題。我正在拍攝:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
我有以下代碼,它給了我這個:
3 2 1
3 2 1
3 2 1
3 2
3
我想我已經很接近了,但有人可以幫忙嗎?
System.out.print("Enter the length of the pattern size: ");
int size = scan.nextInt();
System.out.println();
for (int row=size*2-1; row >= 1; row--) {
for (int col=size*2-1; col >= 1; col--) {
if (col <= size && row >= size-col 1 )
System.out.print(col " ");
}
System.out.println();
}
}
}
uj5u.com熱心網友回復:
我認為問題在于您使用的邏輯。我做了一個受另一個想法啟發的演算法,也許它會對你有所幫助。我相信有比這更簡單的方法,但這也適用于所有數字。
輸入 4 的示例:獲取 x 和 y 值,在最小坐標(x 或 y)之后是應該列印哪個數字的指示符。x 和 y 從 0 開始從左上角向下增加。
例如,如果 x 或 y 坐標為 0,我們知道它將為 4。如果 x 坐標為 2 但 y 為 3,我們仍然取較小的那個:列印出來的數字將在第二個數字圈中,數字 2 .
// 4 4 4 4
// 4 3 3 3
// 4 3 2 2
// 4 3 2 1
System.out.print("Enter the length of the pattern size: ");
int size = scan.nextInt();
System.out.println();
int len = size*2-1; // length of column and row
for (int row = 0; row < len; row ) {
int x = (row%size); // get x coordinate (row)
if (row >= size) x = (size-2) - x; // flip coordinate
for (int col = 0; col < len; col ) {
int y = (col%size); // get y coordinate (col)
if (col >= size) y = (size-2) - y; // flip coordinate
int val = size - Math.min(x, y); // get minimum coordinate
System.out.print(val " ");
}
System.out.println();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489179.html
上一篇:如何遍歷嵌套字典
