Number Diamond Pattern
Problem
Read n (at most 9) and print a diamond of numbers. The top half is the palindromic number pyramid with n rows. The bottom half repeats the rows in reverse order without repeating the widest row.
Constraints
- 1 <= n <= 9
Examples
Input
3
Output
1 121 12321 121 1
Solutions
We reuse the line builder from the palindromic pyramid and call it twice: first with growing rows, then with shrinking rows.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Diamond of numbers.
* Input : One integer n (1 to 9).
* Output : 2n-1 lines.
* Approach: Palindromic pyramid and its mirror.
* 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();
}
// This method receives the half size and a row number. It returns one line, for example 12321.
static String buildLine(int half, int row) {
StringBuilder line = new StringBuilder(repeat(" ", half - row));
for (int number = 1; number <= row; number++) {
line.append(number);
}
for (int number = row - 1; number >= 1; number--) {
line.append(number);
}
return line.toString();
}
public static void main(String[] args) {
int half = new Scanner(System.in).nextInt();
// Step 1: Print the top half. Row numbers go from 1 up to half.
for (int row = 1; row <= half; row++) {
System.out.println(buildLine(half, row));
}
// Step 2: Print the bottom half. Start from half - 1 because the widest row is already printed.
for (int row = half - 1; row >= 1; row--) {
System.out.println(buildLine(half, row));
}
}
}
Hints (2)
- Build one line with a method.
- Call it for the top half and then for the bottom half.