該查詢用於編寫一個Java方法,該方法根據給定的輸入(字母數量,三角形的每邊)輸出以下三角形, 。二維數組(Java) - 按循環順序打印帶有字母的三角形
public void triangle(int side);
輸出預期: 三角形(3)
* * A * *
* F * B *
E * D * C
三角形(4)
* * * A * * *
* * I * B * *
* H * * * C *
G * F * E * D
我想出來的,其不只是一個方法,但代碼我用有限的經驗寫了更多for循環。你們中的任何人都可以查看我的代碼,併爲相同的問題提出建議或優化代碼?
public void triangle(int input) {
int x = input;
int y = 2 * input - 1;
int mid = y/2;
char character = 'A';
String[][] partitionArray1 = new String[x][y];
\\Following for loop will add letters on the side-1
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (i + mid == j) {
partitionArray1[i][j] = "" + character++;
} else {
partitionArray1[i][j] = "*";
}
}
}
\\Following for loop will add letters on the side-2 (horizontal)
for (int j = y - 2; j >= 0; j--) {
j--;
if (j >= 0) {
partitionArray1[x - 1][j] = "" + character++;
} else {
break;
}
}
\\Following for loop will add letters on the side-3
for (int i = x - 2; i >= 0; i--) {
for (int j = 0; j < y; j++) {
if ((i == mid - j) && (j < mid)) {
partitionArray1[i][j] = "" + character++;
}
}
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(partitionArray1[i][j] + "");
}
System.out.println();
}
}
是否有算法可以回答這樣的問題?
相當類似上述的解決做了,但愛的代碼最小化的理念! –
他的解決方案可能類似,它的速度快了7倍 –
完全同意這一點@TaharBakir –