Это другой подход, при котором вычисляет количество spaces
и количество fill
символов, необходимых в строке, а затем использует printf
для печати строк.
public static void printChristmasTree(int height, char ch) {
if (height <= 4)
throw new IllegalArgumentException("Height must be 5 or higher");
for (int row = height; row > 0; row--) {
int spaces = (row > 2 ? row - 3 : height - 4);
int fill = (height - spaces) * 2 - 5;
System.out.printf("%2d|%s%s%s|%d=%d+%d+%d%n", row,
repeat(spaces, ' '), repeat(fill, ch), repeat(spaces, ' '),
spaces * 2 + fill, spaces, fill, spaces);
}
}
private static String repeat(int count, char ch) {
char[] buf = new char[count];
java.util.Arrays.fill(buf, ch);
return new String(buf);
}
Тест
printChristmasTree(10, '*');
printChristmasTree(6, '#');
Выход
10| * |15=7+1+7
9| *** |15=6+3+6
8| ***** |15=5+5+5
7| ******* |15=4+7+4
6| ********* |15=3+9+3
5| *********** |15=2+11+2
4| ************* |15=1+13+1
3|***************|15=0+15+0
2| *** |15=6+3+6
1| *** |15=6+3+6
6| # |7=3+1+3
5| ### |7=2+3+2
4| ##### |7=1+5+1
3|#######|7=0+7+0
2| ### |7=2+3+2
1| ### |7=2+3+2
ОБНОВЛЕНИЕ
Вот логика для высоты ствола height/4
(округленная) вместо фиксированной высоты 2
, используемой приведенным выше кодом.Ширина магистрали по-прежнему фиксирована и составляет 3.
public static void printChristmasTree(int height, char ch) {
final int trunkHeight = (height + 2) / 4; // rounded
final int treeWidth = (height - trunkHeight) * 2 - 1;
final int width = (treeWidth > 3 || trunkHeight == 0 ? treeWidth : 3);
for (int row = height; row > 0; row--) {
int fill = (row > trunkHeight ? (height - row) * 2 + 1 : 3);
int spaces = (width - fill) / 2;
System.out.printf("%2d|%s%s%s|%d=%d+%d+%d%n", row,
repeat(spaces, ' '), repeat(fill, ch), repeat(spaces, ' '),
spaces * 2 + fill, spaces, fill, spaces);
}
}
Тест
printChristmasTree(5, '*');
printChristmasTree(4, '*');
printChristmasTree(3, '*');
printChristmasTree(2, '*');
printChristmasTree(1, '*');
Выход
5| * |7=3+1+3
4| *** |7=2+3+2
3| ***** |7=1+5+1
2|*******|7=0+7+0
1| *** |7=2+3+2
4| * |5=2+1+2
3| *** |5=1+3+1
2|*****|5=0+5+0
1| *** |5=1+3+1
3| * |3=1+1+1
2|***|3=0+3+0
1|***|3=0+3+0
2| * |3=1+1+1
1|***|3=0+3+0
1|*|1=0+1+0