Skip to content
Open

Task9 #826

Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions src/main/java/com/walking/intensive/chapter2/task9/Task9.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,44 @@
*/
public class Task9 {
public static void main(String[] args) {
// Для собственных проверок можете делать любые изменения в этом методе
System.out.println(getPascalTriangle(18));
}

static String getPascalTriangle(int n) {
// Ваш код
return null;
public static String getPascalTriangle(int rows) {
if (rows <= 0 || rows > 35) {
return "";
}
StringBuilder temp = new StringBuilder();
StringBuilder result = new StringBuilder();
int maxLength;

for (int j = 0; j < rows; j++) {
temp.append(getNum(rows - 1, j)).append('\n');
}

maxLength = temp.length() - 1;

for (int i = 0; i < rows; i++) {
temp.delete(0, temp.length());
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Удаление всей строки?) зачем? Не проще новую строку создать? Да и в целом логичнее в новую переменную вынести

for (int j = 0; j <= i; j++) {
temp.append(getNum(i, j)).append(" ");
}
temp.deleteCharAt(temp.length() - 1);
result.append(" ".repeat(Math.max(0, (maxLength - temp.length()) / 2))).append(temp).append('\n');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Math.max(0, (maxLength - temp.length()) / 2) - в переменную с понятным названием.
Кроме того, епочки вызовов лучше оформлять по правилу точка-строчка - каждый новый верхнеуровневый вызов с новой строки. Читается лучше, в более старых версиях джавы (кажется, до 17) облегчит локализацию NullPointerException:

int shift = Math.max(0, (maxLength - temp.length()) / 2); //здесь у тебя еще скобки лишние в вычитании

result.append(" ".repeat(shift))
    .append(temp)
    .append('\n');

}
return result.toString();
}

static int getNum(int rows, int cols) {
if (rows < 0 || cols < 0) {
return 0;
}
if (cols == 0 || rows == cols) {
return 1;
}
if ((cols == 1) || (cols == (rows - 1))) {
return rows;
}
return getNum(rows - 1, cols - 1) + getNum(rows - 1, cols);
}
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Файл должен завершаться пустой строкой https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом, стало намного лучше

Loading