Number Pyramid Pattern
Problem
Read n and print a centered pyramid. Row i contains the number i written i times, separated by one space, with n-i spaces in front.
Constraints
- 1 <= n <= 9
Examples
Input
3
Output
1 2 2 3 3 3
Solutions
It combines the star pyramid idea (leading spaces) with the repeated-number rows. Because each number takes one character and each separator one space, the rows stay centered.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Centered pyramid of repeated numbers.
* Input : One integer n (rows).
* Output : n lines.
* Approach: Spaces first, then the repeated number.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method returns the text repeated "count" times. Java 11 has String.repeat for this.
static String repeat(String text, int count) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++) {
result.append(text);
}
return result.toString();
}
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
// Step 2: Print the spaces first. Row 1 needs the most spaces.
StringBuilder line = new StringBuilder(repeat(" ", rows - row));
// Step 3: Write the row number "row" times with one space between them.
for (int count = 1; count <= row; count++) {
if (count > 1) {
line.append(" ");
}
line.append(row);
}
// Step 4: Print the finished line.
System.out.println(line);
}
}
}
Hints (1)
- Which two patterns are combined here?