Diamond Star Pattern
Problem
Read n and print a diamond of stars. The top half is a pyramid with n rows. The bottom half is the same pyramid upside down without repeating the widest row. The diamond has 2n-1 rows.
Constraints
- 1 <= n <= 50
Examples
Input
3
Output
* *** ***** *** *
Solutions
A diamond is a pyramid followed by an upside-down pyramid. We reuse one method for both halves and skip the widest row the second time.
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 stars.
* Input : One integer n (rows in the top half).
* Output : 2n-1 lines.
* Approach: Print a pyramid and then print it again in reverse order.
* 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 of the pyramid.
static String buildLine(int half, int row) {
return repeat(" ", half - row) + repeat("*", 2 * row - 1);
}
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)
- Split the diamond into two halves.
- Write one method that builds one line and call it in two loops.