查询是编写一个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();
}
}
是否有可用于解决此类问题的算法?
答案 0 :(得分:1)
尝试:
public static void triangle(int n) {
for (int i = 0; i < n; ++i) {
if (i == n-1) {
for (int j = 0; j < 2*n-1; ++j)
if (j % 2 == 0)
System.out.printf("%c ", 'A' + 2*n-2-j/2);
else
System.out.printf("* ");
System.out.println();
break;
}
for (int j = 0; j < 2*n-1; ++j) {
if (j == n-1+i)
System.out.printf("%c ", 'A'+i);
else if (j == n-1-i)
System.out.printf("%c ", 'A'+3*n-i-3);
else
System.out.printf("* ");
}
System.out.println();
}
}
这个想法是将行#n
与另一行分开打印。该行的其余部分恰好有两个元素(除了第一个是退化的情况)相对于中心对称。
triangle(9);
* * * * * * * * A * * * * * * * *
* * * * * * * X * B * * * * * * *
* * * * * * W * * * C * * * * * *
* * * * * V * * * * * D * * * * *
* * * * U * * * * * * * E * * * *
* * * T * * * * * * * * * F * * *
* * S * * * * * * * * * * * G * *
* R * * * * * * * * * * * * * H *
Q * P * O * N * M * L * K * J * I
答案 1 :(得分:1)
我很无聊所以我用一个阵列做了
public static void mimi(int size){
int sizetab=size*size*2;
char res[] = new char[sizetab];
Arrays.fill(res,'*');
int pos=size-1;
int JumpGoRight=(2*size)+1;
int JumpGoLeft=2;
char letter='A';
boolean changed = false;
int nbLetters = size -1;
for (int s=size;s>1;s--)
nbLetters+=2;
int i=0;
while(i<(size-1)){
res[pos]=letter++;
pos+=JumpGoRight;
i++;
}
int limit=(sizetab-(size*2))+1;
while(i<nbLetters){
res[pos]=letter++;
pos-=JumpGoLeft;
if( !changed && (pos<limit) ){
JumpGoLeft=(size*2)-1 ;
changed=true;
}
i++;
}
int index = 0;
int doublesize=size*2;
for(char c: res){
if( ((++index)%doublesize)==0)
System.out.print('\n');
else
System.out.print(c);
}
}